LETTERS = "abc"
correct = "cab "
guess = ""
while guess != correct:
for i in LETTERS:
position = random.randrange(len(LETTERS))
guess += LETTERS[position]
LETTERS = LETTERS[:position] + LETTERS[(position + 1):]
print(guess)
我是Python的新手,我想制作这个简单的程序:
我想出了这个代码,它给了我一个无限循环。我无法弄清楚为什么这样做。我确信这很容易,但我看不到它。需要一些帮助!谢谢!
答案 0 :(得分:3)
我可以看到三个问题:
"cab "
中有空格,LETTERS
没有空格。所以你永远无法猜出一个空间guess
。你只是不断添加LETTERS
,因此在while循环的第二次迭代中,它将完全为空。这就是我要做你想做的事情(只做最少的修改):
_LETTERS = "abc"
correct = "cab"
guess = ""
while guess != correct:
LETTERS = _LETTERS[:]
guess = ""
for i in LETTERS:
position = random.randrange(len(LETTERS))
guess += LETTERS[position]
LETTERS = LETTERS[:position] + LETTERS[(position + 1):]
print(guess)
以下是我将如何进行随机搜索(这是您正在尝试做的事情):
guess = "abc"
correct = "cab"
while guess != correct:
guess = list(guess)
random.shuffle(guess)
guess = ''.join(guess)
print(guess)
print(guess)
当然,有更好的技巧可以正确猜测"cab"
。如果您真的想尝试详尽的搜索,那么您可以使用回溯DFS:
def DFS(letters, correct, sofar=None)
if sofar is None:
sofar = ''
if not letters:
if sofar == correct:
print("Yay! I found it")
else:
print("Oops! I found %s instead" %sofar)
else:
for i,char in enumerate(letters):
DFS(letters[:i]+letters[i+1:], correct, sofar+char)
答案 1 :(得分:2)
您的correct
值包含空格,但您的循环永远不会生成空格:
correct = "cab "
删除该空格:
correct = "cab"
接下来,你的循环将LETTERS
缩减为空字符串,因此只有一次,你的循环会产生一个随机guess
,但之后,你永远会被{{{ 1}},所以没有运行LETTERS = ''
循环。
最好使用for
进行猜测:
random.shuffle