【问题标题】:Guessing Game python binary search猜谜游戏python二分搜索
【发布时间】:2014-05-04 01:43:10
【问题描述】:

我无法弄清楚我的代码有什么问题。我试图让用户想到一个介于 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()  

【问题讨论】:

    标签: python


    【解决方案1】:

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

    其他一些问题:

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

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

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

    • 第 14 行:应该是lo = 1

    • 第 19 行:a 是什么?你从来不用它。

    • 第 20-22 行:您确实需要保留所有可能数字的列表,只需保留您已经拥有的最低和最高可能值(lo 和 @987654333 @),如果你做了你可以做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()  
    

    【讨论】:

    • 我需要在第 29 行输入字符串部分,然后用户输入 1、-1 或 0
    • @user3500257:然后测试if (user_response == "1"):,否则它不会工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多