I am trying to make the computer use a bisection search to guess a number I entered that is from 0 to 100. Now, for all the numbers I enter the computer can guess within 7 tries, all except 100, where it goes into an infinite loop. I know why that happens, it's because I have int(high+low)/2 so the closest the program would get to 100 would be 99.5 ( high=100, low=99) which would be rounded to 99. so the program will keep guessing 99. How can I modify my code so that it deals with this, without have to specifically guess the number 100 using an if statement?
print("This is a bisection search, which I hopefully am going to beat. HAHAHA!")
for i in range(99999**9):
high=100
low=0
number_of_searches=1
print('enter a guess between 0 and 100')
user_input = int(input())
guess = int((high+low)/2)
while user_input != guess:
if guess>user_input:
high=guess
else:
low=guess
number_of_searches+=1
guess=int((high+low)/2)
print (" your number was found in ",number_of_searches, "search
es")
You can just set high to 101 and it will find it.
print("This is a bisection search, which I hopefully am going to beat. HAHAHA!")
for i in range(99999**9):
high=101
low=0
number_of_searches=1
print('enter a guess between 0 and 100')
user_input = int(input())
guess = int((high+low)/2)
while user_input != guess:
if guess>user_input:
high=guess
else:
low=guess
number_of_searches+=1
guess=int((high+low)/2)
print (" your number was found in ",number_of_searches, "searches")
This will get into an infinite loop if you try to look for 101 though. So just set max to be 1 more than the actual max you want to be able to search for.