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

    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

09-15 12:27