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 0 · Your binary search

Goal: a folder for this course with its lab script, your own search(a, x) using the window [lo, hi), a small tool that counts how many elements it reads on a million numbers, and two bugs you cause on purpose and watch the checker catch.

Time: ~30 minutes. Where: your own computer: files in ~/binary-search-intro/, commands in a terminal in that folder. Needs Python 3.9 or newer and curl. Read lesson 1 and lesson 2 first.

Task 1 · Get the lab

Make the folder everything in this course goes into, and download the course’s lab script into it:

mkdir -p ~/binary-search-intro
cd ~/binary-search-intro
curl -fo lab http://localhost:8800/binary-search-intro/tools/lab
chmod +x lab
./lab setup p0

It prints:

  ✓ Python 3.13.5 (3.9 or newer)
  ✓ nothing to download: you write every file of this course yourself

ready for p0. Next: write bsearch.py (task 2), then ./lab check p0

Your Python version may differ; anything from 3.9 up is fine.

What setup did

Only checked your Python: this course has no given files and no containers. ./lab alone lists what it can do:

CommandWhat it does
./lab check p0imports your bsearch.py and calls search in a separate process with a 10-second limit, so an endless loop is reported instead of freezing your terminal; it only reads your files
./lab reset p0asks first, then moves your bsearch.py and rounds.py into a new folder before-reset-<date>/; nothing is deleted
./lab updatereplaces the lab script with the newest copy from the book

Every command setup, reset and update run goes to lab.log in the folder.

Create ~/binary-search-intro/bsearch.py yourself, with one function:

  • name search(a, x); a is a sorted list (smallest first), possibly empty
  • returns an index i with a[i] == x, or -1 if x isn’t in a
  • uses the window [lo, hi) from lesson 2: lo is in it, hi is not
  • doesn’t slice the list (a[lo:hi] copies it: as much work as a scan) and doesn’t use the bisect module
Hint

Start with the whole list as the window: lo = 0, hi = len(a). Loop while the window isn’t empty. Each round: mid from lo and hi; if a[mid] is too small, lo moves past mid; if it’s too big, hi moves to mid (hi isn’t in the window, so that already leaves mid out). After the loop: not found.

Solution
# ~/binary-search-intro/bsearch.py

def search(a, x):
    """Index of x in the sorted list a, or -1 if x isn't there."""
    lo, hi = 0, len(a)              # the window [lo, hi): lo is in it, hi is not
    while lo < hi:                  # the window isn't empty
        mid = (lo + hi) // 2        # lo <= mid < hi: always inside the window
        if a[mid] < x:
            lo = mid + 1            # x can only be right of mid
        elif a[mid] > x:
            hi = mid                # x can only be left of mid; mid leaves, since hi is not in the window
        else:
            return mid
    return -1                       # the window is empty: x isn't in a

Try the edges: an empty list, one element found and not found, the first and last of three, and a gap:

python3 -c "from bsearch import search; print(search([], 5), search([7], 7), search([7], 3), search([1, 3, 5], 1), search([1, 3, 5], 5), search([1, 3, 5], 4))"

You should see:

-1 0 -1 0 2 -1

Task 3 · Count the looks

Lesson 1 said at most 20 rounds for a million numbers. Measure it on your own code. Create ~/binary-search-intro/rounds.py:

  • run as python3 rounds.py N X: searches for X in the sorted numbers 0, 1, ..., N-1 with your search
  • prints one line ending with how many times search read an element (a[i])
  • counts with a subclass of list whose __getitem__ adds one to a counter, then reads the element as usual
Hint

class Peek(list): with a class attribute looks = 0 and a __getitem__(self, i) that increments Peek.looks and returns super().__getitem__(i). Peek(range(n)) makes the list. sys.argv[1] and sys.argv[2] are the arguments, as strings: int() them.

Solution
# ~/binary-search-intro/rounds.py
import sys

from bsearch import search


class Peek(list):
    """A list that counts how many times an element is read."""
    looks = 0

    def __getitem__(self, i):
        Peek.looks += 1
        return super().__getitem__(i)


n, x = int(sys.argv[1]), int(sys.argv[2])
a = Peek(range(n))                  # the sorted numbers 0, 1, ..., n-1
r = search(a, x)
print(f"n={n:,} x={x}: result {r}, looked at {Peek.looks} elements")

Predict first: a million numbers take at most 20 rounds. How many reads does rounds.py report for -1 (smaller than all of them)? And for 999999, the last number?

python3 rounds.py 1000000 -1
python3 rounds.py 1000000 999999
What you see
n=1,000,000 x=-1: result -1, looked at 40 elements
n=1,000,000 x=999999: result 999999, looked at 20 elements

40, then 20. Look at the if: for -1, a[mid] < x is false in every one of the 20 rounds, so the elif reads a[mid] a second time: 2 reads a round. 999999 is found in 19 rounds: in each of the first 18, a[mid] < x is true and one read is enough; the last round reads twice before reaching else. To always read once, store it first: v = a[mid], then compare v.

Now double the list:

python3 rounds.py 2000000 -1
n=2,000,000 x=-1: result -1, looked at 42 elements

Twice the numbers, one more round (two more reads).

Task 4 · Break it: one too many

In bsearch.py, change hi = mid to hi = mid - 1. Lesson 2’s Check yourself 3 predicted what happens:

python3 -c "from bsearch import search; print(search([1, 3, 5], 1), search([1, 3, 5], 3), search([1, 3, 5], 5))"
-1 1 2

No error: 1 is reported missing, the others are found. Run the checker and see how it finds the failing input for you (it prints a second FAIL too, on big lists, and ends with 11/13 passed):

./lab check p0
  FAIL right on every list of 0-5 items, for x below, at, between and above the elements
       wrong for a=[10, 20], x=10: returned -1, expected 0

Now find why, in this order:

  1. Take the smallest failing input the checker gave: search([10, 20], 10).
  2. Trace it by hand: lo = 0, hi = 2, mid = 1; a[1] = 20 > 10, so hi = mid - 1 = 0. The window [0, 0) is empty, but 10 is at position 0.
  3. Check the line against the promise: hi is not in the window, so hi = mid already removes mid. mid - 1 throws out position 0 too, where x still could be.

Put hi = mid back.

Task 5 · Break it: never stops

Change lo = mid + 1 to lo = mid, and run the checker:

./lab check p0

After 10 seconds, among its lines (it ends with 7/8 passed: the checks after the stuck call never ran):

  FAIL a call never returned within 10 s: an endless loop?
       last call: search([10], 15)

The checker stopped the process and shows the call it was stuck in. Trace it: lo = 0, hi = 1, mid = 0; a[0] = 10 < 15, so lo = mid = 0. Nothing changed, so the next round is the same round. lo = mid breaks the rule that every round removes mid from the window, and with // rounding down, mid == lo happens whenever the window has one element (or two).

Put lo = mid + 1 back.

Check your work

./lab check p0
13/13 passed
Go deeper: why the checker tries every list of 0 to 5 items

Off-by-one bugs live at the edges: an empty list (the loop must not run), one element (mid == lo), two (where rounding down matters), and x below the first or above the last. The checker searches every sorted list of 0 to 5 items for values below, at, between and above its elements, so the failing case it reports is small enough to trace by hand, as in task 4. Big random lists then catch what’s left.

Next: lesson 3 · First, last, and where it would go.