gpt4 book ai didi

python - 猜算法好像不行,用Python猜数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:33:21 25 4
gpt4 key购买 nike

我正在努力研究一些简单的算法,该算法应该让 python 以尽可能少的猜测来猜测给定的数字。它似乎在运行,但速度非常慢。我究竟做错了什么。我已经阅读了几个关于这个问题的主题,但找不到解决方案。我是一名初级程序员,欢迎任何提示。

min = 1
max = 50

number = int(input(("please choose a number between 1 and 50: ")))

total = 0
guessed = 0

while guessed != 1:
guess = int((min+max)/2)
total += 1

if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
min = guess + 1
elif guess < number:
max = guess - 1

谢谢

附言。我知道该程序不会检查错误输入;)

最佳答案

你的逻辑是倒退的。当您猜得太高时,您希望降低 max 并在您猜得太低时提高 min。试试这个:

if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
max = guess - 1
elif guess < number:
min = guess + 1

关于python - 猜算法好像不行,用Python猜数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29842760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com