Search code examples
pythonbisection

Bisection search code doesnt work


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

Solution

  • 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