Editor

Most Checks for Binary Search

Intermediate · Write the code · from Linear Search and Binary Search: Counting the Checks

From the lesson: Linear Search and Binary Search: Counting the Checks

Searching a list means checking elements until you find the one you want, and the method you choose decides whether that takes 3 checks or 3 million. Linear search works on any list. Binary search is far faster on big lists, but it only works when the data is sorted.

Read the lesson

Write max_checks(n) that returns the maximum number of checks binary search needs on a sorted list of n elements.

Use the halving method: while n is greater than 0, count one check and replace n with n // 2 (the most elements that can be left after a check).

max_checks(7)     ->  3
max_checks(100)   ->  7
def max_checks(n):
# Count how many times you can halve n before it reaches 0
pass

What Check runs

Your code runs first, then each of these lines, and 2 more that stay hidden. The output must match exactly.

RunsExpected output
max_checks(7)3
max_checks(100)7
max_checks(1)1

More Linear and Binary Search exercises

All Python exercises · 50 practice problems