你能解释一下我这个代码出了什么问题吗?我想做一个二分搜索,它接受输入数字并重复二分搜索,直到它找到与输入相同的数字并打印出各种语句。
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
答案 0 :(得分:1)
首先,您不需要输入猜测。你总是会从你的射程的中点开始。
相反,等待让用户想到一个数字,然后猜测。
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.")
第二个问题,你需要&#34;划分&#34;你的搜索空间。如果猜测太高,则将该猜测设置为最大值,如果设置得太低,则将其设置为最小值。在任何一种情况下都无需设置其他值;它保持不变。
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