The Python Game Book

code games. learn Python.

User Tools

Site Tools


Sidebar

Github:

en:glossary:b:binary_search

In computer science, binary search, also known as half-interval search logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array

This simple number guessing game demonstartes binary search: The user must think of a number between 0 and 1,000,000 and the computer guesses the number. The user only gives feedback if the number is too high or too low:

"""binary search example - number guessing game"""
print("""
I, the computer, will use binary search algorithm to guess a number.
Please think of an integer number between one and one million.
""")

lower_limit = 0
upper_limit = 1000000
prompt=("is this too (h)igh or too (l)ow or (c)orrect ?")
guess = 1
while True:
    g = lower_limit + (upper_limit - lower_limit)//2
    print("i guess your number is", g)
    answer = input(prompt+" >>>").lower()
    if answer not in ("h", "l", "c"):
        continue 
    if answer == "h":
        upper_limit = g
    elif answer == "l":
        lower_limit = g
    else:
        break
    guess += 1
print("i guessed your number in using {} questions".format(guess))

en/glossary/b/binary_search.txt · Last modified: 2020/05/30 20:56 by horst