我写了一个简单的猜谜游戏和猜猜它的方法......
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 次,并且问题是错误的。