0
def highlowR():
    play_again = 1
    while play_again==1:
        ct = 0
        guess = 50
        x = 0
        ans = ""
        print "Lets play a game. \nThink of a number between 1 and 100.\n"
        while ans!="c":
            temp0 = 0
            temp1 = 0
            print "I guess %d" %guess
            ans = raw_input("Am I too (h)igh, too (l)ow, or (c)orrect? \n")
            if ans=="h":
                temp0 = guess/2
                temp1 = guess%2
                guess = temp0 + temp1
            elif ans=="l":
                temp0 = guess/2
                temp1 = guess%2
                guess = guess + temp0 + temp1
            elif ans=="c":
                print "I got it! It only took me %d guesses." %ct
            else:
                print "I didn't quite understand what you meant there."
            ct = ct+1
        play_again = input("Would you like to play again? Yes = 1, No = 0: ")
        print""
    print "Thanks for playing!"
highlowR()

我几乎有一个正在运行的反向高低游戏,但我不知道如何更改我的 if 语句中的数学以优化我的结果。如果要猜测的数字是 1,它会起作用......但我不知道该怎么做才能优化我的结果。有什么帮助吗?

4

1 回答 1

0

我不知道您要对 temp0 和 temp1 做什么。将最小值和最大值保存在内存中要好得多。像这样的东西应该工作:

def highlowR():
    play_again = 1
    while play_again==1:
        ct = 0
        max = 10
        min = 0
        guess = 0
        x = 0
        ans = ""
        print "Lets play a game. \nThink of a number between 1 and %d.\n"%max
        while ans!="c":
            if (max+min)/2 == guess:
                print "I think you lied to me at some point. The answer is definitely %d" %guess
                break
            guess = (max+min)/2
            print "I guess %d" %guess
            ans = raw_input("Am I too (h)igh, too (l)ow, or (c)orrect? \n")
            if ans=="h":
                max = guess
            elif ans=="l":
                min = guess
            elif ans=="c":
                print "I got it! It only took me %d guesses." %ct
            else:
                print "I didn't quite understand what you meant there."
            ct = ct+1
        play_again = input("Would you like to play again? Yes = 1, No = 0: ")
        print""
    print "Thanks for playing!"
highlowR()
于 2013-10-07T13:17:02.153 回答