On Saturday the crew plays a guessing game in the maker space. Comet thinks of a number from 1 to 100. Wren guesses, and she answers only "higher" or "lower".
Wren starts at 1, then 2, then 3. Comet groans. "This could take a hundred guesses!"
"What does the evidence say?" Wren asks, and changes his plan. "Fifty." Then "twenty-five." Then "thirty-seven." He has it in three.
Nova projects the number line shrinking by half after each answer. "How can I help?" she asks. "That is binary search with people. Count the guesses."
Comet points at you. "Lead programmer, try it with your family."
Wren checked the middle strategy with a program that plays every secret number from 1 to 100.
# guess_count.py
def guesses(secret):
"""How many middle guesses find secret, from 1 to 100."""
low = 1
high = 100
count = 0
while True:
guess = (low + high) // 2
count += 1
if guess == secret:
return count
elif guess < secret:
low = guess + 1
else:
high = guess - 1
most = 0
for secret in range(1, 101):
if guesses(secret) > most:
most = guesses(secret)
print(guesses(50))
print(guesses(37))
print(most) 1 3 7
Wonderful searching this week. Next week the crew sorts the catalog, so binary search has sorted data to work on.