
Checkpoint: The Sorted Logbook
The Guild logbook lists lantern serial numbers, sorted from
smallest to largest. Inspectors keep asking: "How many lanterns
have serials between lo and hi?"
The logbook is huge, so checking every entry (O(n)) is too slow. Binary search can answer in about log₂ n steps instead.
Lower bound
lower_bound(items, target) returns the first index whose item
is >= target. If every item is smaller, it returns len(items).
items: [3, 5, 5, 8, 12]
lower_bound(items, 5) -> 1 (first 5)
lower_bound(items, 6) -> 3 (8 is the first item >= 6)
lower_bound(items, 99) -> 5 (nothing is big enough)
It is binary search with one twist. Keep a range lo..hi that
always contains the answer, starting with 0..len(items):
- If
items[mid] < target, the answer is to the right ofmid. - Otherwise
miditself might be the answer, so keep it in range.
Stop when lo == hi. That is the answer.
Counting a range
For whole numbers, the items between lo and hi (both included)
start at lower_bound(items, lo) and end just before
lower_bound(items, hi + 1). Subtract to count them.
Assignment
lower_bound(items, target): use binary search as described. Don't loop over every item, and don't use thebisectmodule.count_between(items, lo, hi): return how many itemsxhavelo <= x <= hi. Calllower_boundtwice.
lower_bound(items, target): use binary search as described. Don't loop over every item, and don't use thebisectmodule.count_between(items, lo, hi): return how many itemsxhavelo <= x <= hi. Calllower_boundtwice.
Press Run to try your code, then Check to test it.