猜猜游戏python二进制搜索

时间:2014-05-04 01:43:10

标签: python

我无法弄清楚我的代码出了什么问题。我试图让用户想到1到100之间的数字,然后这个程序将能够猜到它。程序会添加范围的高位数和低数,并除以2并将其用作猜测。如果程序猜测的数字高于其数字,则用户输入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()  

1 个答案:

答案 0 :(得分:1)

你的主要问题在第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()