【问题标题】:Why does my algorithm stop after a while? [closed]为什么我的算法会在一段时间后停止? [关闭]
【发布时间】:2021-06-04 02:58:01
【问题描述】:

我写了一个算法来猜测用户输入的数字:

import random

def innum(x):
    innumber = ""
    for y in range(x):
        innumber += str(y)
    return innumber

def ml():
    wrong = ""
    while True:
        guess = start
        action = random.choice(["+","-"])
        if action == "+":
            guess += random.randint(0,1000)
        if action == "-":
            guess -= random.randint(0,1000)
        if "-" not in str(guess):
            if str(guess) not in wrong:
                if guess == answer:
                    print("Correct: " + str(answer))
                    break
                else:
                    print("Wrong:" + str(guess))
                    wrong += str(guess)
start = random.randint(0,1000)
answer = input("What number to go to from " + str(start) + ". Has to be in range 2000.")
if answer in innum(2000):
        ml()
else:
     print("Number not in range 2000.")

但是过了一会儿它就停止了,我多次运行它,它一直停止并且永远不会得到答案。程序我看了好几遍,还是不知道为什么会停止。

【问题讨论】:

  • 什么ai()
  • 修复了抱歉我刚才改了名字
  • 尝试在if "-" not in str(guess之后添加以下两个调试打印:print("Got here, str(guess) is " + str(guess))print("Got here, wrong is " + wrong)

标签: python algorithm random


【解决方案1】:

经过一些测试,我会假设条件if str(guess) not in wrong: 在执行一段时间后永远不会为真。由于程序会随着时间的推移使用许多不同的数字组合填充wrong,因此str(guess) 最终将位于wrong 之间。

【讨论】:

    【解决方案2】:

    问题是if str(guess) not in wrong: 会检查值是否不在字符串中。但是一旦遇到该值,if 语句就会返回False,因此程序会停止。但是,while 循环中没有停止。

    【讨论】:

      最近更新 更多