Lesson 9: Binary search

posted Dec 19, 2019, 8:02 AM by Attila Lengyel
target = int(input("Think of a number:"))
lower = 1
upper = 100

while target < 1 or target > 100:
print("Please think between 1 and 99!")
target = int(input("Try again:"))

guess = 0

import math
while guess != target:
guess = lower + math.floor((upper - lower)/2)
print("Is the number", guess, "? (yes/lower/higher):")
answer = input()
if answer == "yes":
print("I knew it!!!")
elif answer == "lower":
upper = guess - 1
elif answer == "higher":
lower = guess + 1

Comments