python - 猜号游戏优化(用户创号,电脑猜号)

标签 python algorithm python-3.x

我是编程新手,所以大约 4 或 5 天前我决定开始使用 Python。我遇到了一个挑战,要求我创建一个“猜数字”游戏。完成后,“硬挑战”是创建用户创建数字并由计算机(AI)猜测的猜数字游戏。

到目前为止,我已经想到了这个并且它有效,但它可能会更好,我会解释。

from random import randint

print ("In this program you will enter a number between 1 - 100."
       "\nAfter the computer will try to guess your number!")

number = 0

while number < 1 or number >100:
    number = int(input("\n\nEnter a number for the computer to guess: "))
    if number > 100:
        print ("Number must be lower than or equal to 100!")
    if number < 1:
        print ("Number must be greater than or equal to 1!")

guess = randint(1, 100)

print ("The computer takes a guess...", guess)

while guess != number:
    if guess > number:
        guess -= 1
        guess = randint(1, guess)
    else:
        guess += 1
        guess = randint(guess, 100)
    print ("The computer takes a guess...", guess)

print ("The computer guessed", guess, "and it was correct!")

这是我上次运行时发生的事情:

输入一个数字让电脑猜:78

计算机猜测... 74

计算机猜测... 89

计算机猜测... 55

计算机猜测... 78

计算机猜对了 78!

请注意,它有效,但是当计算机猜出 74 时,它会猜出一个更大的数字,即 89。这个数字太高,所以计算机猜出一个较小的数字,但选择的数字是 55。有没有办法让我可以让计算机猜测一个小于 89 但大于 74 的数字吗?这是否需要额外的变量或更复杂的 if、elif、else 语句?

谢谢 Ryan Haining

我使用了您回复中的代码并稍作修改,因此猜测始终是随机的。如果您看到这个,请告诉我这是否是最好的方法。

from random import randint

def computer_guess(num):
    low = 1
    high = 100
    # This will make the computer's first guess random
    guess = randint(1,100)
    while guess != num:
        print("The computer takes a guess...", guess)
        if guess > num:
            high = guess
        elif guess < num:
            low = guess + 1
        # having the next guess be after the elif statement
        # will allow for the random guess to take place
        # instead of the first guess being 50 each time
        # or whatever the outcome of your low+high division
        guess = (low+high)//2    

    print("The computer guessed", guess, "and it was correct!")


def main():
    num = int(input("Enter a number: "))
    if num < 1 or num > 100:
        print("Must be in range [1, 100]")
    else:
        computer_guess(num)

if __name__ == '__main__':
    main()

最佳答案

你要的就是经典binary search algorithm

def computer_guess(num):
    low = 1
    high = 100
    guess = (low+high)//2
    while guess != num:
        guess = (low+high)//2
        print("The computer takes a guess...", guess)
        if guess > num:
            high = guess
        elif guess < num:
            low = guess + 1

    print("The computer guessed", guess, "and it was correct!")


def main():
    num = int(input("Enter a number: "))
    if num < 1 or num > 100:
        print("Must be in range [1, 100]")
    else:
        computer_guess(num)

if __name__ == '__main__':
    main()

该算法通过选择开始时的下限和上限(在您的情况下为 low=1 和 high=100)来工作。然后检查它们之间的中点。

如果中点小于数字,则中点成为新的下界。如果中点更高,它将成为新的上限。执行此操作后,将在上限和下限之间生成一个新的中点。

为了举例说明,假设您正在寻找 82。

这是一个示例运行

Enter a number: 82
The computer takes a guess... 50
The computer takes a guess... 75
The computer takes a guess... 88
The computer takes a guess... 82
The computer guessed 82 and it was correct!

那么每一步都发生了什么?

  1. low = 1, high = 100 => guess = 50 50 < 82 所以 low = 51
  2. low = 51, high = 100 => guess = 75 75 < 82 所以 low = 76
  3. low = 76, high = 100 => guess = 88 88 > 82 所以high = 88
  4. low = 76, high = 88 => guess = 82 82 == 82 我们就完成了。

注意这个的时间复杂度是O(lg(N))

关于python - 猜号游戏优化(用户创号,电脑猜号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17877870/

相关文章:

python - Pyside:QLineEdit 接受多个输入

python - 打印日期时间对象列表时覆盖默认格式

java - 如何使用 JPype 在 Python 中导入用户构建的 jar?

Python "builtins.TypeError: must be str, not bytes"- Twisted LineReceiver.sendLine()

python - 当我们在Django中使用opencv时如何处理请求

algorithm - K-封闭最小面积正方形

algorithm - 简单游戏编程的数学/算法(新手)?

java - 这段代码有什么问题?霍夫曼编码

django - 无法将目标WSGI脚本'/var/www/backend/backend/wsgi.py'加载为Python模块

python - 使用OpenCV Python检测复杂形状