pythonbinarybinary-searchdivide-and-conquer

How can I adjust my code to use binary search to guess the number I am thinking in my head


This code needs to ask the user for a number (ie: 32). Then it should tell the user to pick a number from 1 to 31. Then binary search would be used to "guess" a number (16 not 15) then the user would type if that number is correct, too high, or too low. Also I figure that having some sort of function in the code would make it more sensible, but I don't know how to implement it.

I had the user enter a number, then start to guess what they were thinking starting at 16 if the original number was 32. However if I said H for the 16 being too high, it would output 24 which is an even higher number than 16.

import numpy as np
low = 0
n = int(input("Enter n: "))

if n <= 0:
    n = int(input("Please enter a positive number: "))
else:
    array = np.arange(0, n, 1)  # Fix the range to include 0 and n-1
    print(f'Guess a number between 0 and {n - 1}')

    while low <= n - 1:  # Correct the condition to use n - 1
        guess = low + (n - low) // 2  # Fix the calculation for the guess
        answer = input(f'Is your number: {guess}? Please enter C for correct, H for too high, or L for too low.')

        if answer == 'C':
            break
        elif answer == 'H':
            n = guess  # Adjust the range for a lower guess
        else:
            low = guess + 1  # Adjust the range for a higher guess

Solution

  • import numpy as np
    
    def binary_search(low, high):
        while low <= high:
            guess = low + (high - low) // 2
            answer = input(f'Is your number: {guess}? Please enter C for correct, H for too high, or L for too low.')
    
            if answer == 'C':
                print(f'Your number is {guess}.')
                return
            elif answer == 'H':
                high = guess - 1 
            else:
                low = guess + 1  
    
        print("Hmm, it seems like there was an error with the inputs.")
    
    n = int(input("Enter n: "))
    
    
    if n <= 0:
        n = int(input("Please enter a positive number: "))
    
    
    print(f'Guess a number between 0 and {n - 1}')
    binary_search(0, n - 1)
    

    Did few changes and Now think it runs fine. Also added a little bonus of the message when the number is guessed. Most importantly Simplified it by separating out the binary search from it.