【问题标题】:Can a bisection search guess that the user guessed the highest value?二分搜索可以猜测用户猜到了最高值吗?
【发布时间】:2021-06-04 12:33:43
【问题描述】:

我正在尝试让计算机使用二分搜索来猜测我输入的从 0 到 100 的数字。现在,对于我输入的所有数字,计算机可以在 7 次尝试内猜到,除了 100 之外,它会去哪里进入无限循环。我知道为什么会这样,这是因为我有 int(high+low)/2 所以程序最接近 100 的是 99.5(high=100,low=99),它会四舍五入到 99。所以程序会继续猜测 99。如何修改我的代码以便它处理这个问题,而不必使用 if 语句专门猜测数字 100?

print("This is a bisection search, which I hopefully am going to beat. HAHAHA!")
for i in range(99999**9):
    high=100
    low=0
    number_of_searches=1
    print('enter a guess between 0 and 100')
    user_input =  int(input())
    
    guess = int((high+low)/2)
    while user_input != guess:
        if guess>user_input:
            high=guess
        else:
            low=guess 
        number_of_searches+=1
        guess=int((high+low)/2)
        
    print (" your number was found in ",number_of_searches, "search

es")

【问题讨论】:

    标签: python bisection


    【解决方案1】:

    您可以将高设置为 101,它会找到它。

    print("This is a bisection search, which I hopefully am going to beat. HAHAHA!")
    for i in range(99999**9):
        high=101
        low=0
        number_of_searches=1
        print('enter a guess between 0 and 100')
        user_input =  int(input())
    
        guess = int((high+low)/2)
        while user_input != guess:
            if guess>user_input:
                high=guess
            else:
                low=guess 
            number_of_searches+=1
            guess=int((high+low)/2)
    
        print (" your number was found in ",number_of_searches, "searches")
    

    如果您尝试查找 101,这将进入无限循环。因此,只需将 max 设置为比您希望能够搜索的实际最大值大 1 即可。

    【讨论】:

    • 哇!太精彩了。很简单。非常感谢兄弟
    猜你喜欢
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    相关资源
    最近更新 更多