Guessing Game python binary search

猜谜游戏python二进制搜索

Tags: python
标签: python

问题 (Question)

I can't figure out what's wrong with my code here. I am trying to have the user think of a number between 1 and 100 and then this program will be able to guess it. The program adds the high and low numbers of the range and divides by two and uses that as the guess. The user enters a 1 if the number the program guess is higher than their number, -1 if it is lower, and 0 if the guess is correct. After at most 7 guesses the number guessed should be right. When I run my code it constantly prints out the guess as 50 and never changes. It seems to never be running through the if statements. It should be running through the program and finding a new guess.

def main():
    import random
    print("Guessing Game")
    print("")
    print("Think of a number 1 and 100 inclusive.\nAnd I will guess what it is in 7 tries or less.")
    print("")
    ready = input("Are you ready? (y/n): ")
    print("")
    if ready != "y" and ready != "n":
        ready = input("Are you ready? (y/n): ")
    if ready == "n":
        print("Bye")
    if ready == "y":
        lo = 0
        hi = 100
        guess_high = 1
        guess_same = 0
        guess_low = -1  
        a = random.randint(1,100)
        num_list = []
        for i in range(1,100):
            num_list.append(i)
        while (lo <= hi):
            guess_count = 0
            for guess_count in range(1,8):
                guess_count += 1
                guess = (lo + hi) // 2
                print("Guess",guess_count," : The number you thought was",guess)
                user_response = input("Enter 1 if my guess was high, -1 if low, and 0 if correct: ")
                if (user_response == 1):
                    hi = guess - 1
                    guess_count += 1
                    guess = (lo + hi) // 2
                elif (user_response == -1):
                    lo = guess + 1
                    guess_count += 1
                    guess = (lo + hi) // 2
                elif (user_response == 0):
                    print("Thank you for playing the Guessing Game.")
main()  

我不明白怎么了我的代码在这里。我想有用户认为1和100之间的数字,然后这个程序能猜它。程序添加了高、低数量的两种,使用的范围和分裂的猜测。用户输入一个1如果程序猜测是高于他们的数量,1如果低,0如果猜想是正确的。后最多7猜测猜数应该是正确的。当我运行我的代码它不断输出猜测50,从不改变。它似乎永远不会运行在if语句。它应该贯穿程序,找到一个新的猜测。

def main():
    import random
    print("Guessing Game")
    print("")
    print("Think of a number 1 and 100 inclusive.\nAnd I will guess what it is in 7 tries or less.")
    print("")
    ready = input("Are you ready? (y/n): ")
    print("")
    if ready != "y" and ready != "n":
        ready = input("Are you ready? (y/n): ")
    if ready == "n":
        print("Bye")
    if ready == "y":
        lo = 0
        hi = 100
        guess_high = 1
        guess_same = 0
        guess_low = -1  
        a = random.randint(1,100)
        num_list = []
        for i in range(1,100):
            num_list.append(i)
        while (lo <= hi):
            guess_count = 0
            for guess_count in range(1,8):
                guess_count += 1
                guess = (lo + hi) // 2
                print("Guess",guess_count," : The number you thought was",guess)
                user_response = input("Enter 1 if my guess was high, -1 if low, and 0 if correct: ")
                if (user_response == 1):
                    hi = guess - 1
                    guess_count += 1
                    guess = (lo + hi) // 2
                elif (user_response == -1):
                    lo = guess + 1
                    guess_count += 1
                    guess = (lo + hi) // 2
                elif (user_response == 0):
                    print("Thank you for playing the Guessing Game.")
main()  

最佳答案 (Best Answer)

Your main problem is in lines 29, 30, 34, 38: input() returns a string, but you are testing against an int. "1" is not equal to 1!

Some other problems:

  • line 2: import random should not be in main()

  • lines 7-10: getting a yes/no response for ready should be done in a while loop or (better) in its own function - repeat until a valid response is gotten

  • lines 9, 11, 13: you need to learn about else and elif

  • line 14: should be lo = 1

  • line 19: what is a for? You never use it.

  • lines 20-22: you do not need to keep a list of every possible number, just the lowest and highest possible values, which you already have (lo and hi), and if you did you could do num_list = list(range(1, 100))

  • lines 25, 26, 32, 36: incrementing guess_count is useless and unnecessary because it is reset each time you re-enter the for loop

Here is a cleaned-up version:

# assumes Python 3
def get_yn(prompt, yes_values={"y", "yes"}, no_values={"n", "no"}):
    """
    Prompt for a yes or no response;
    return True for yes or False for no
    """
    while True:
        response = input(prompt).strip().lower()
        if response in yes_values:
            return True
        elif response in no_values:
            return False

def get_int(prompt, lo=None, hi=None):
    """
    Prompt for a number,
    return as int
    """
    while True:
        try:
            value = int(input(prompt))
            if (lo is None or lo <= value) and (hi is None or value <= hi):
                return Value
        except ValueError:
            pass

def get_one_of(prompt, values):
    """
    Prompt for a response in values,
    return response string
    """
    while True:
        value = input(prompt).strip().lower()
        if value in values:
            return value

def main():
    print(
        "Guessing Game\n"
        "\n"
        "Think of a number in [1..100],\n"
        "and I will try to guess it in no more than 7 tries.\n"
    )

    if get_yn("Are you ready? (y/n): "):
        lo, hi = 1, 100
        got_it = False
        for attempt in range(1, 8):
            guess = (lo + hi) // 2
            print("I guess {}!".format(guess))
            res = get_one_of("Was this [L]ow, [H]igh, or [C]orrect? ", {"l", "h", "c"})            
            if res == "l":
                lo = guess + 1
            elif res == "h":
                hi = guess - 1
            else:  # correct!
                got_it = True
                break
            if lo > hi:
                break
        if got_it:
            print("Ha! Got it in {} guesses!".format(attempt))
        else:
            print("Something smells in the state of Denmark...")
    else:
        print("Bye!")

if __name__=="__main__":
    main()  

��的主要问题是行29、30、34岁38:input()返回一个字符串,但是您正在测试一个int。"1"不等于1 !

一些其他问题:

  • 第2行:import random不应该在main()

  • 行7 - 10:是的/没有响应ready应该做的吗while循环或(更好的)的函数-重复,直到得到一个有效的响应

  • 行9、11、13:你需要了解elseelif

  • 第14行:应该lo = 1

  • 19行:是什么a为了什么?你不使用它。

  • 行20 - 22:你不需要保持所有可能的数字列表,只是最低和最高可能的值,您已经有(lohi),如果你做了你能做的num_list = list(range(1, 100))

  • 25、26日,32岁的36:递增guess_count是无用的和不必要的,因为它是重置每次你进入for循环

这是一个清理的版本:

# assumes Python 3
def get_yn(prompt, yes_values={"y", "yes"}, no_values={"n", "no"}):
    """
    Prompt for a yes or no response;
    return True for yes or False for no
    """
    while True:
        response = input(prompt).strip().lower()
        if response in yes_values:
            return True
        elif response in no_values:
            return False

def get_int(prompt, lo=None, hi=None):
    """
    Prompt for a number,
    return as int
    """
    while True:
        try:
            value = int(input(prompt))
            if (lo is None or lo <= value) and (hi is None or value <= hi):
                return Value
        except ValueError:
            pass

def get_one_of(prompt, values):
    """
    Prompt for a response in values,
    return response string
    """
    while True:
        value = input(prompt).strip().lower()
        if value in values:
            return value

def main():
    print(
        "Guessing Game\n"
        "\n"
        "Think of a number in [1..100],\n"
        "and I will try to guess it in no more than 7 tries.\n"
    )

    if get_yn("Are you ready? (y/n): "):
        lo, hi = 1, 100
        got_it = False
        for attempt in range(1, 8):
            guess = (lo + hi) // 2
            print("I guess {}!".format(guess))
            res = get_one_of("Was this [L]ow, [H]igh, or [C]orrect? ", {"l", "h", "c"})            
            if res == "l":
                lo = guess + 1
            elif res == "h":
                hi = guess - 1
            else:  # correct!
                got_it = True
                break
            if lo > hi:
                break
        if got_it:
            print("Ha! Got it in {} guesses!".format(attempt))
        else:
            print("Something smells in the state of Denmark...")
    else:
        print("Bye!")

if __name__=="__main__":
    main()  

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/23451688