我写了一个简单的猜谜游戏和猜测它的方法......
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次,问题是错误的。
答案 0 :(得分:2)
>>> from math import log, ceil
>>> ceil(log(1000, 2))
10.0
答案 1 :(得分:1)
让我们看看:
A number between 1 and 1 requires 1 guess
A number between 1 and 3 requires 2 guesses at most
A number between 1 and 7 requires 3 guesses at most
A number between 1 and 15 requires 4 guesses at most
A number between 1 and 31 requires 5 guesses at most
...
换句话说,n
猜测足以覆盖从1
到(2**n)-1
的范围。
对于n=10
,此范围是1
到1023
。自1023 >= 1000
以来,您对十个猜测的结论是正确的。
也就是说,您用来验证此结论的代码是错误的,因为每当您转到下一个数字时,它都无法重新初始化big
和small
以及guesses
。此外,您可以只测试1到1000之间的每个数字,而不是随机生成数字,并使用具有有限运行时间的确定性算法。