Bisection search code doesnt work [closed]

感情迁移 提交于 2019-12-13 08:36:09

问题


Could you explain where i'm going wrong with this code? I want to do a bisection search which takes input number and repeats bisection search until it finds the same number as input and prints out various statements.

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

回答1:


Firstly, you don't need to input a guess. You are always going to start at the mid-point of your range.

So, instead, wait for the user to think of a number, then guess.

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.")

Second problem, you need to "divide" your search space. If the guess is too high, set that guess as the maximum, if too low, set that as the minimum. No need to set the other value in either case; it stays the same.

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

And lastly, you need to update average each time through the loop to generate a new guess.

    average = (minimum + maximum) / 2.0


来源:https://stackoverflow.com/questions/39501407/bisection-search-code-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!