对分搜索码

2024-05-17 01:19:55 发布

您现在位置:Python中文网/ 问答频道 /正文

你能解释一下我的代码哪里出错了吗?我想做一个二分法搜索,它接受输入数字并重复二分法搜索,直到它找到与输入相同的数字并打印出各种语句。你知道吗

num =int( input("Please think of a number between 0 and 100!"))
maximum = num
minimum = 0
average = (minimum+maximum)/2.0

while(average<num):
 print ("Is your secret number ", +average, "?")  
 cond = input("Enter 'h' to indicate the guess is too high.Enter 'l' to indicate the guess is too low.Enter 'c' to indicate I guessed correctly.")

 if( cond == "h"):
    maximum = minimum
    minimum = 0
 elif(cond == "l"):
    minimum = maximum
    maximum = 100
 elif(cond == "c"): 
    print("Game over. Your secret number was: ", +average)
    break

Tags: thetonumberinputsecret数字numprint
1条回答
网友
1楼 · 发布于 2024-05-17 01:19:55

首先,你不需要输入猜测。你总是从你的射程的中点开始。你知道吗

因此,相反,等待让用户想到一个数字,然后猜测。你知道吗

import time

minimum = 0
maximum = 100
print("Please think of a number between {} and {}!".format(minimum, maximum))
time.sleep(3)

average = (minimum + maximum)/2.0

while(True):
    print ("Is your secret number ", +average, "?")  
    cond = input("Enter 'h' to indicate the guess is too high.Enter 'l' to indicate the guess is too low.Enter 'c' to indicate I guessed correctly.")

第二个问题,你需要“划分”你的搜索空间。如果猜测过高,则将该猜测设置为最大值,如果猜测过低,则将其设置为最小值。在这两种情况下都不需要设置另一个值;它保持不变。你知道吗

    if( cond == "h"):
        maximum = average
    elif(cond == "l"):
        minimum = average
    elif(cond == "c"): 
        print("Game over. Your secret number was: ", +average)
        break

最后,您需要每次通过循环更新average,以生成新的猜测。你知道吗

    average = (minimum + maximum) / 2.0

相关问题 更多 >