gpt4 book ai didi

python - 执行二分查找来猜测随机数,但猜测的数量不匹配

转载 作者:行者123 更新时间:2023-11-30 23:37:26 24 4
gpt4 key购买 nike

我写了一个简单的猜谜游戏和猜谜的方法...

    from gasp import *

number = random_between(1, 1000)
guesses = 0

while True:
guess = input("Guess the number between 1 and 1000: ")
guesses += 1
if guess > number:
print "Too high!"
elif guess < number:
print "Too low!"
else:
print "\n\nCongratulations, you got it in %d guesses!\n\n" % guesses
break

现在根据问题,如果使用正确的策略,最大猜测次数应等于 11。我使用二分搜索来获得正确的数字,但猜测次数永远不会超过 10。要检查我执行了以下操作并产生了一个非终止循环。

    from gasp import *


guesses = 0
big = 1000
small = 1
while guesses != 11
number = random_between(1, 1000)
while True:
guess = (big + small) / 2
guesses += 1
if guess > number:
print "Too high!"
big = guess
elif guess < number:
print "Too low!"
small = guess
else:
print "\n\nCongratulations, you got it in %d guesses!\n\n" % guesses
break

那么谁是对的,是我犯了一些错误,还是需要猜测的次数不能超过 10 次,问题就错了。

最佳答案

>>> from math import log, ceil
>>> ceil(log(1000, 2))
10.0

关于python - 执行二分查找来猜测随机数,但猜测的数量不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15586314/

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