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 に答える