Python高低游戏逆转优化

时间:2013-10-07 03:47:50

标签: python

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,它就可以工作......但是我无法弄清楚该怎么做才能优化我的结果。有什么帮助吗?

1 个答案:

答案 0 :(得分: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()