Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Practical 1 · Capstone: range counts from an empty folder

Goal: in a new folder ranges/, your own lower_bound, upper_bound, first, last and insert_at, checked against Python’s bisect on thousands of lists full of repeats; then a tool that answers “how many events between A and B?” with two searches. Then you swap one < and break a time’s format on purpose, and watch what each one costs.

Time: ~40 minutes. Where: your own computer: files in ~/binary-search-intro/ranges/, commands in a terminal in that folder. Read lesson 3 first.

cd ~/binary-search-intro
./lab setup p1
  ✓ Python 3.13.5 (3.9 or newer)
  ✓ ranges/events.txt: 100,000 event times from one day, sorted, one per line

ready for p1. Next: write ranges/bounds.py (task 2), then ./lab check p1

Your copy of lab says doesn't know p1 yet? Run ./lab update first. Skipped Practical 0? ./lab reset p1 starts you here with its solution in place.

What setup did

It made the folder ranges/ and wrote events.txt in it: 100,000 times between 08:00:00 and 17:59:59, sorted, made from a fixed random seed, so your file is the same as the one this page was tested on and your counts match it. The data isn’t what this practical teaches; every .py file in ranges/ is yours to write. Run it again and it keeps the events.txt you have.

Task 1 · Look at the data

cd ranges
head -3 events.txt
tail -1 events.txt
wc -l events.txt
08:00:00
08:00:00
08:00:00
17:59:59
100000 events.txt

The same second appears many times: this is exactly the list with repeats that lesson 3 was about.

Each time is a string, HH:MM:SS, always two digits each. Strings of the same fixed width compare like the times they stand for: "09:05:00" < "10:00:00" because "0" < "1", character by character. So you can search the strings as they are, with no conversion. Task 5 shows what happens when the width isn’t fixed.

Task 2 · Write the five functions

Create ~/binary-search-intro/ranges/bounds.py yourself:

FunctionReturns
lower_bound(a, x)the first index i with a[i] >= x, or len(a)
upper_bound(a, x)the first index i with a[i] > x, or len(a)
first(a, x)the index of the first copy of x, or -1
last(a, x)the index of the last copy of x, or -1
insert_at(a, x)where x would go so a stays sorted, before any copies already there
  • the window [lo, hi) and no early exit: each bound runs until the window is empty
  • first, last and insert_at call the bounds; they don’t loop themselves
  • no slicing, no bisect (the checker uses bisect to compare)
Hint

Lesson 3’s “How it works” has lower_bound in full. upper_bound is the same loop with one character changed. For the other three, lesson 3’s table “Everything from two edges”: each is one line plus a check that the index is inside the list and holds x.

Solution
# ~/binary-search-intro/ranges/bounds.py

def lower_bound(a, x):
    """First index i with a[i] >= x, or len(a) if there is none."""
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1        # mid is too small: the edge is right of it
        else:
            hi = mid            # a[mid] >= x: the edge is at mid or left of it
    return lo                   # lo == hi: the edge


def upper_bound(a, x):
    """First index i with a[i] > x, or len(a) if there is none."""
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] <= x:
            lo = mid + 1        # mid is x or smaller: the edge is right of it
        else:
            hi = mid            # a[mid] > x: the edge is at mid or left of it
    return lo


def first(a, x):
    """Index of the first copy of x, or -1."""
    i = lower_bound(a, x)
    return i if i < len(a) and a[i] == x else -1


def last(a, x):
    """Index of the last copy of x, or -1."""
    i = upper_bound(a, x) - 1
    return i if i >= 0 and a[i] == x else -1


def insert_at(a, x):
    """Where x would go so a stays sorted: before any copies of x already there."""
    return lower_bound(a, x)

Try them on lesson 3’s list, for 8 (three copies) and 10 (none):

python3 -c "from bounds import *; a = [2, 8, 8, 8, 12, 16, 23, 38, 56, 72]; print(lower_bound(a, 8), upper_bound(a, 8), first(a, 8), last(a, 8), insert_at(a, 8)); print(first(a, 10), last(a, 10), insert_at(a, 10))"
1 4 1 3 1
-1 -1 4

The same numbers as lesson 3’s table.

Task 3 · Count a range

Create ~/binary-search-intro/ranges/count.py, run as python3 count.py FILE FROM TO:

  • reads the sorted times in FILE into a list, one per line
  • prints one line that starts with the count of times t with FROM <= t <= TO, e.g. 179 events from 09:00:00 to 09:00:59
  • uses two searches from bounds.py, as lesson 3’s Check yourself 2 worked out, and no loop over the list
  • FROM after TO prints a count of 0, never a negative number
  • a time that isn’t HH:MM:SS (9:00:00) stops the program with a message and a non-zero exit status
Hint

from bounds import lower_bound, upper_bound works because count.py sits next to bounds.py. The arguments are sys.argv[1:]. The lower bound of FROM is the first time in range; the upper bound of TO is the first one after it. re.fullmatch(r"\d\d:\d\d:\d\d", t) checks a time’s format; sys.exit("message") stops with status 1. max(0, ...) handles FROM after TO.

Solution
# ~/binary-search-intro/ranges/count.py
import re
import sys

from bounds import lower_bound, upper_bound

if len(sys.argv) != 4:
    sys.exit("usage: python3 count.py FILE FROM TO   (times as HH:MM:SS)")
path, start, end = sys.argv[1:]
for t in (start, end):
    if not re.fullmatch(r"\d\d:\d\d:\d\d", t):
        sys.exit(f"{t} is not HH:MM:SS: write it with two digits each, like 09:05:00")

with open(path) as f:
    times = [line.strip() for line in f]      # already sorted: the file is in time order

n = max(0, upper_bound(times, end) - lower_bound(times, start))
print(f"{n} events from {start} to {end}")

Predict first: the file holds 100,000 events spread over ten hours. About how many fall in the hour from 09:00:00 to 09:59:59?

python3 count.py events.txt 09:00:00 09:59:59
What you see
10099 events from 09:00:00 to 09:59:59

About a tenth, as the spread predicts. Count the same hour another way, with a tool that reads every line:

grep -c '^09:' events.txt
10099

The same number. grep compared every line. Once the list is in memory, your two searches look at 17 positions each at most, though count.py still reads the whole file to build it (Go deeper, below).

One second, FROM equal to TO, counts the copies of that one time (lesson 3: upper - lower):

python3 count.py events.txt 12:00:00 12:00:00
4 events from 12:00:00 to 12:00:00

Task 4 · Break it: one < too many

In bounds.py, in lower_bound only, change if a[mid] < x: to if a[mid] <= x:.

Predict first: what does the same one-second question print now?

python3 count.py events.txt 12:00:00 12:00:00
python3 count.py events.txt 09:00:00 09:59:59
0 events from 12:00:00 to 12:00:00
10098 events from 09:00:00 to 09:59:59

No error, and the hour is off by just one: the single event at exactly 09:00:00. Now the checker:

./lab check p1

Among its lines (the 10 PASS lines are left out):

  FAIL lower_bound agrees with bisect_left: every list of 0-5 items, then 2,000 random lists full of repeats
       lower_bound([10], 10) returned 1, expected 0
  FAIL first agrees with bisect_left: every list of 0-5 items, then 2,000 random lists full of repeats
       first([10], 10) returned -1, expected 0
  FAIL insert_at agrees with bisect_left: every list of 0-5 items, then 2,000 random lists full of repeats
       insert_at([10], 10) returned 1, expected 0
  FAIL count.py 09:00:00 10:00:00 on a 9-line file 08:00,08:00,09:00,09:00,09:00,09:30,10:00,10:00,11:15: 3 (expected 6)
       it printed: 3 events from 09:00:00 to 10:00:00

10/14 passed

Four FAILs from one character: first, insert_at and count.py all call lower_bound, so start with the function the others are built on. Find why, in this order:

  1. Take the smallest failing input: lower_bound([10], 10).
  2. Trace it: lo = 0, hi = 1, mid = 0; a[0] = 10 <= 10, so lo = 1. The window is empty at 1, past the 10.
  3. Ask what an equal value should do: for the lower bound, an equal a[mid] may be the first copy, so it must stay in play (hi = mid). <= sends it away, and lower_bound turns into upper_bound.

Put < back.

Task 5 · Break it: a time without its zero

In count.py, comment out the three lines that check the format (the for, its if and the sys.exit). Then ask for 08:00:00 to 9:59:59, a time anyone might type.

Predict first: with the check gone, what does it count? (Task 1: strings compare character by character.)

python3 count.py events.txt 08:00:00 9:59:59
100000 events from 08:00:00 to 9:59:59

Every event of the day, up to 17:59. The search did exactly what it was asked: as strings, "9:59:59" is bigger than "17:59:59", because the first characters already differ and "9" > "1". A binary search is only as right as the order it searches; the format check is what keeps every string the same width. Put the three lines back and see the refusal:

python3 count.py events.txt 08:00:00 9:59:59
9:59:59 is not HH:MM:SS: write it with two digits each, like 09:05:00

Check your work

cd ~/binary-search-intro
./lab check p1
23/23 passed

It compares your five functions with bisect_left and bisect_right on every list of 0 to 5 items made of 10, 20 and 30, then on 2,000 random lists of up to 60 numbers from 0 to 9 (many repeats), counts how many positions each bound reads on a million items, and runs your count.py on a small file, your events.txt, FROM after TO and 9:00:00, counting how often it calls each bound.

Go deeper: where the time goes

count.py reads the whole file every time it runs, and reading is a scan. To see what each part costs, put this in ranges/timing.py:

import time

from bounds import lower_bound, upper_bound
t0 = time.perf_counter()
with open('events.txt') as f:
    times = [line.strip() for line in f]
t1 = time.perf_counter()
n = upper_bound(times, '09:59:59') - lower_bound(times, '09:00:00')
t2 = time.perf_counter()
k = sum(1 for t in times if '09:00:00' <= t <= '09:59:59')
t3 = time.perf_counter()
print(f"read the file: {(t1-t0)*1000:.1f} ms; two searches: {(t2-t1)*1e6:.1f} us ({n}); one scan of the list: {(t3-t2)*1000:.1f} ms ({k})")

On the machine this course was written on, in one run:

read the file: 38.5 ms; two searches: 51.1 us (10099); one scan of the list: 18.5 ms (10099)

The two searches take about 51 microseconds, the scan about 360 times as long, and reading the file twice as long again. For one question, the file read is the cost. Binary search pays off when the sorted list is loaded once and asked many times: a server holding the day’s events in memory answers each range question in two searches. Your numbers will differ with the machine; the proportions are what to look at.

Next: you’ve built the whole family from an empty folder. Flag anything that was unclear, wrong or too wordy: select it and press Flag.