Skip to main content
 首页 » 编程设计

python之猜谜游戏python二进制搜索

2024年11月01日7me-sa

我不知道我的代码有什么问题。我试图让用户想出 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()   

请您参考如下方法:

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

其他一些问题:

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

  • 第 7-10 行:获取对 ready 的是/否响应应该在 while 循环或(更好)在它自己的函数中完成 - 重复直到得到一个有效的回应

  • 第 9、11、13 行:您需要了解 else 和 elif

  • 第 14 行:应该是 lo = 1

  • 第 19 行:a 有什么用?你永远不会使用它。

  • 第 20-22 行:您不需要保留一个包含每个可能数字的列表,只需保留您已经拥有的最低和最高可能值(lo 和 hi),如果你做了,你可以做 num_list = list(range(1, 100))

    /li>
  • 第 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()