17. Algorithms and data structures
Most data work is a few classic problems in disguise. Find the first reading after 14:05. Put 3,000 house prices into price bands. Rank 30 products by revenue. Match two card transactions that add up to a disputed amount. Find the longest run of growing daily revenue. Each problem has a slow, obvious solution and a fast one. The fast one uses the right algorithm with the right data structure. This module teaches the dozen patterns that solve most of these problems, and it shows you how to prove that one solution is faster than another by counting its operations.
What you will learn
Section titled “What you will learn”- Count the operations of an algorithm and read its growth as big-O: constant, logarithmic, linear, linearithmic and quadratic time.
- Search sorted data with a hand-written binary search, then with
bisect_left,bisect_rightandinsort. - Sort records with
key, several keys and stable passes, write merge sort by hand, and explain whysorted()is fast. - Use stacks, queues (
deque) and heaps (heapq) for undo, bracket matching, tree walks, top-k rankings, stream merging and task queues. - Solve counting, grouping and matching problems with hash maps, two pointers and sliding windows.
- Choose between recursion and iteration, and know the recursion limit and memoization.
Prerequisites
Section titled “Prerequisites”- 04. Data structures: lists, dicts, sets, tuples and the first big-O ideas (constant, linear and quadratic time).
- 05. Functions:
sorted()withkey, lambda, recursion and the call stack. - 07. Files and data formats:
csv.DictReaderandwith open(...). - 09. Standard library power tools:
Counter,defaultdict,dequeandfunctools.cache. - 10. Iterators and generators: lazy streams and sliding windows.
- 15. Performance and concurrency: big-O basics and why you measure before you optimize.
Concepts
Section titled “Concepts”Algorithms and how to compare them
Section titled “Algorithms and how to compare them”An algorithm is a precise list of steps that solves a problem, such as “find the first sensor reading after 14:05”. Many algorithms solve the same problem. They differ in how much work they do as the data grows.
You could time two algorithms with a stopwatch. Timings change with the laptop, the other programs that run and the Python version. This module uses a steadier measure: the operation count, the number of basic steps (comparisons, additions, list accesses) that an algorithm makes. You add a counter to the code and print it. The count is the same on every machine, so the outputs on this page are exact.
Here is the simplest search. It looks at each price in turn until it finds the target. This is a linear search: it can look at every element once.
prices = [14.99, 19.99, 24.5, 34.99, 59.99, 79.99, 129.95, 249.0, 1149.0]
def linear_search(values: list[float], target: float) -> tuple[int, int]: """Return (index of target or -1, number of comparisons).""" comparisons = 0 for i, value in enumerate(values): comparisons += 1 if value == target: return i, comparisons return -1, comparisons
print(linear_search(prices, 14.99)) # the first elementprint(linear_search(prices, 1149.0)) # the last elementprint(linear_search(prices, 99.0)) # not in the list(0, 1)(8, 9)(-1, 9)The count depends on the input. The best case is the input that needs the fewest operations: the target is first, 1 comparison. The worst case is the input that needs the most: the target is last or missing, comparisons for prices. Big-O usually describes the worst case, because it is a guarantee. Linear search is : double the data, double the work.
Module 04 introduced big-O notation with constant time , linear time and quadratic time . This module adds two more classes:
- Logarithmic time, : the work grows by one step each time the data doubles. Binary search is .
- Linearithmic time, : times a logarithm. Good sorting algorithms are .
The logarithm answers “how many times can I halve before one element is left?”. This table shows why the classes matter:
import math
print(f"{'n':>13} {'log2 n':>7} {'n log2 n':>15} {'n squared':>25}")for n in [10, 1_000, 1_000_000, 1_000_000_000]: log_n = math.ceil(math.log2(n)) print(f"{n:>13,} {log_n:>7} {n * log_n:>15,} {n * n:>25,}") n log2 n n log2 n n squared 10 4 40 100 1,000 10 10,000 1,000,000 1,000,000 20 20,000,000 1,000,000,000,0001,000,000,000 30 30,000,000,000 1,000,000,000,000,000,000For a million rows, a logarithmic search needs about 20 steps and a linear search a million. A quadratic algorithm needs a trillion steps: hours instead of a blink. The jump from to or is the most important speed-up in this module.
Memory counts too. Space complexity is how the extra memory of an algorithm grows with . An in-place algorithm changes its input directly and needs only extra memory; list.sort() sorts in place, sorted() builds a new list.
Binary search: halve the data at every step
Section titled “Binary search: halve the data at every step”Sensor S1 in data/sensors.csv logs a reading every 10 minutes for 14 days: 2,016 readings, sorted by time. A precondition is a condition that must be true before an algorithm runs. Binary search has one: the data must be sorted. Sorted data lets you skip most of it.
Binary search looks at the middle element. If the middle is too small, the answer lies in the right half; otherwise it lies in the left half. Each comparison halves the part that is left to search.
flowchart TD
A["lo = 0, hi = len(values)"] --> B{"lo < hi?"}
B -- no --> R["return lo"]
B -- yes --> M["mid = (lo + hi) // 2"]
M --> C{"values[mid] < target?"}
C -- yes --> L["lo = mid + 1"]
C -- no --> H["hi = mid"]
L --> B
H --> B
This version returns the first index whose value is greater than or equal to the target. That position is the insertion point: the index where the target would go to keep the list sorted. The interval [lo, hi) always holds the answer. It is half-open: it includes lo and excludes hi.
def binary_search(values: list[float], target: float) -> tuple[int, int]: """Return (first index with values[i] >= target, comparisons). values is sorted.""" lo, hi = 0, len(values) comparisons = 0 while lo < hi: mid = (lo + hi) // 2 comparisons += 1 print(f"lo={lo} mid={mid} hi={hi} value={values[mid]}") if values[mid] < target: lo = mid + 1 # the answer is right of mid else: hi = mid # mid itself may be the answer return lo, comparisons
print(binary_search(prices, 129.95))lo=0 mid=4 hi=9 value=59.99lo=5 mid=7 hi=9 value=249.0lo=5 mid=6 hi=7 value=129.95lo=5 mid=5 hi=6 value=79.99(6, 4)Nine prices need at most 4 comparisons. When the loop ends, lo == hi and that is the answer: index 6, price 129.95. To test if the target is present, check i < len(values) and values[i] == target. In general, binary search on elements makes at most
comparisons. For the 2,016 readings of S1, that is 11. Linear search can need 2,016.
The bisect module
Section titled “The bisect module”The standard library module bisect implements binary search in C. It has the same insertion-point logic as the function above, without the counter:
| Function | Returns or does | With duplicates of x |
|---|---|---|
bisect_left(a, x) |
first index i with a[i] >= x |
the index of the first copy (the gap just before it) |
bisect_right(a, x) (alias bisect) |
first index i with a[i] > x |
the index after the last copy |
insort(a, x) (alias insort_right) |
inserts x and keeps a sorted |
after the existing copies |
insort_left(a, x) |
inserts x and keeps a sorted |
before the existing copies |
from bisect import bisect_left, bisect_right, insort
sock_prices = [14.99, 14.99, 14.99, 19.99, 24.5]print(bisect_left(sock_prices, 14.99), bisect_right(sock_prices, 14.99))print(bisect_left(sock_prices, 20.0), bisect_left(sock_prices, 99.0))copies = bisect_right(sock_prices, 14.99) - bisect_left(sock_prices, 14.99)print("copies of 14.99:", copies)
insort(sock_prices, 15.99)print(sock_prices)0 34 5copies of 14.99: 3[14.99, 14.99, 14.99, 15.99, 19.99, 24.5]bisect_right - bisect_left counts the copies of a value, or the values in a range, in . insort finds the position in , but inserting into a list shifts the elements after it, so one insort is . For many inserts, append everything and sort once.
Since Python 3.10, every bisect function takes a key argument, so you can search a sorted list of records by one field. In bisect_left and bisect_right, the key is applied to the list elements only, so you pass the searched value itself. In insort, the key is applied to the new element too.
readings = [("2024-05-01T00:00:00", 20.21), ("2024-05-01T00:10:00", 20.3), ("2024-05-01T00:20:00", 20.18)]i = bisect_left(readings, "2024-05-01T00:05:00", key=lambda r: r[0])print(i, readings[i])1 ('2024-05-01T00:10:00', 20.3)ISO timestamps such as 2024-05-01T00:10:00 sort as text in time order, because every field has a fixed width and the biggest unit comes first. So you can binary-search them as strings.
Sorting with keys, several keys and stable passes
Section titled “Sorting with keys, several keys and stable passes”Module 05 showed sorted(values, key=...). Here is the full toolkit:
| Tool | Does |
|---|---|
sorted(iterable) |
returns a new sorted list; the input is unchanged |
lst.sort() |
sorts the list in place and returns None |
key=func |
sorts by func(element); Python calls func once per element |
reverse=True |
largest first; ties keep their original order |
key=lambda r: (r["a"], r["b"]) |
multi-key sort: by a, then by b to break ties |
operator.itemgetter("a", "b") |
a fast key that returns the tuple (r["a"], r["b"]) |
key=lambda r: (r["a"], -r["n"]) |
a ascending, numeric n descending |
A tuple key works because Python compares tuples element by element: the second elements only matter when the first ones are equal. To mix directions with a text field, negation does not work (-"West" is an error). Use the stability of the sort instead. A stable sort keeps elements with equal keys in their original order. Sort by the secondary key first, then by the primary key:
from operator import itemgetter
lines = [ {"order_id": "O000004", "region": "West", "revenue": 224.1}, {"order_id": "O000005", "region": "East", "revenue": 116.96}, {"order_id": "O000006", "region": "East", "revenue": 2183.1}, {"order_id": "O000008", "region": "West", "revenue": 119.0},]by_revenue = sorted(lines, key=itemgetter("revenue"), reverse=True)by_region_desc = sorted(by_revenue, key=itemgetter("region"), reverse=True)for line in by_region_desc: print(line["region"], line["revenue"], line["order_id"])West 224.1 O000004West 119.0 O000008East 2183.1 O000006East 116.96 O000005The second sort orders the regions (West before East, descending). Inside each region, it keeps the order of the first sort, so the revenue stays descending. Each pass is , so two passes cost twice as much, not times as much.
How sorting works: merge sort and Timsort
Section titled “How sorting works: merge sort and Timsort”Merge sort is a divide and conquer algorithm: it splits the problem into smaller problems of the same kind, solves them, and combines the answers. It splits the list into two halves, sorts each half (with merge sort again), and merges the two sorted halves. Merging is easy: compare the fronts of the two halves and take the smaller one.
def merge_sort(values: list[float], counter: list[int]) -> list[float]: """Return a sorted copy; counter[0] counts the comparisons.""" if len(values) <= 1: return values[:] # base case: 0 or 1 element is already sorted mid = len(values) // 2 left = merge_sort(values[:mid], counter) right = merge_sort(values[mid:], counter) merged: list[float] = [] i = j = 0 while i < len(left) and j < len(right): counter[0] += 1 if left[i] <= right[j]: # <= keeps equal values in order: stable merged.append(left[i]) i += 1 else: merged.append(right[j]) j += 1 merged.extend(left[i:]) # one side is empty; the other is already sorted merged.extend(right[j:]) return merged
counter = [0]daily_units = [41, 38, 52, 38, 61, 45, 39, 57]print(merge_sort(daily_units, counter), "comparisons:", counter[0])[38, 38, 39, 41, 45, 52, 57, 61] comparisons: 16The list is halved times, and each level of halving merges all elements once. So merge sort is in every case. The counter is a one-element list, because a function can change a list that it receives (module 04, references).
Python’s sorted() and list.sort() use Timsort, a hybrid of merge sort and insertion sort designed for real data. It first finds runs: stretches of the data that are already in order (or in reverse order). Then it merges the runs. Real data often has long runs: log files are almost sorted by time, and new rows arrive at the end. On sorted input, Timsort finds one run and stops after comparisons. Its worst case is still , and it is stable.
You can count the comparisons that sorted() makes. functools.cmp_to_key turns a comparison function into a key, and the comparison function counts its calls:
import randomfrom functools import cmp_to_key
def count_sort_comparisons(values: list[float]) -> int: calls = 0
def compare(a: float, b: float) -> int: nonlocal calls calls += 1 return (a > b) - (a < b) # -1, 0 or 1
sorted(values, key=cmp_to_key(compare)) return calls
ordered = list(range(10_000))shuffled = ordered[:]random.Random(42).shuffle(shuffled)print("already sorted:", count_sort_comparisons(ordered))print("reversed: ", count_sort_comparisons(ordered[::-1]))print("shuffled: ", count_sort_comparisons(shuffled))print("n log2 n: ", round(10_000 * math.log2(10_000)))already sorted: 9999reversed: 9999shuffled: 120215n log2 n: 132877Sorted and reversed input cost comparisons: one run each. Shuffled input costs close to . Sorting 10,000 numbers takes about 120,000 comparisons, not 100 million as a quadratic sort would.
Stacks: last in, first out
Section titled “Stacks: last in, first out”A stack is a collection where you add and remove items at the same end, the top. The last item added is the first one removed. This rule is LIFO (last in, first out). Adding an item is a push. Removing the top item is a pop. A Python list is a good stack: append() pushes and pop() pops, both in amortized time.
Stacks solve problems where the most recent thing must be handled first: the undo history of an editor, the call stack of Python itself (module 05), and nested brackets, where each ] must close the most recent open [.
history: list[str] = []for step in ["drop duplicates", "strip spaces", "fill missing prices"]: history.append(step) # pushprint("undo:", history.pop()) # pop: the most recent stepprint("still applied:", history)undo: fill missing pricesstill applied: ['drop duplicates', 'strip spaces']Queues: first in, first out
Section titled “Queues: first in, first out”A queue serves items in arrival order. The rule is FIFO (first in, first out): add at the back, remove at the front. Module 09 introduced collections.deque, which adds and removes at both ends in . A list is a bad queue: list.pop(0) shifts every remaining element one place left, so it is .
from collections import deque
jobs = deque(["load sales", "load stores"])jobs.append("join tables") # enqueue at the backfirst = jobs.popleft() # dequeue from the frontprint(first, "| waiting:", list(jobs))load sales | waiting: ['load stores', 'join tables']| Need | Structure | Add | Remove |
|---|---|---|---|
| stack (LIFO) | list |
append(x) |
pop() |
| queue (FIFO) | deque |
append(x) |
popleft() |
| both ends | deque |
append, appendleft |
pop, popleft |
last n items only |
deque(maxlen=n) |
append(x) drops the oldest |
Trees and graph walks
Section titled “Trees and graph walks”A tree is a structure of nodes connected parent to child, with no loops. The top node is the root. A node with no children is a leaf. Product catalogs, folder structures, org charts and nested JSON are trees. In Python, a dict that maps each node to the list of its children stores a tree well. This dict is an adjacency list. It also stores a graph, the general case where any node can connect to any other node, loops included.
flowchart TD
A["All products"] --> E["Electronics"]
A --> S["Sports"]
E --> AU["Audio"]
E --> C["Computers"]
AU --> P1["Wireless Earbuds"]
AU --> P2["Noise-Cancelling Headphones"]
C --> P4["14-inch Ultrabook Laptop"]
S --> P17["Non-Slip Yoga Mat"]
Two orders visit every node:
- Breadth-first search (BFS) visits the tree level by level: the root, then all its children, then all grandchildren. It keeps a queue of nodes to visit. On a graph, BFS finds the fewest steps from a start node to every other node.
- Depth-first search (DFS) follows one branch to its leaf before it backs up and tries the next. It uses a stack, or recursion, which uses the call stack.
Worked example 5 builds both.
Heaps and priority queues
Section titled “Heaps and priority queues”A priority queue always serves the item with the best priority next, whatever the arrival order: the most urgent pipeline task, the cheapest offer, the earliest timestamp. A sorted list would do it, but every insert costs . A heap does it faster.
A heap is a list arranged so that each element is smaller than or equal to its two children. The children of index sit at and . This rule is the heap property:
So heap[0] is always the smallest element. This is a min-heap. The rest of the list is only partly ordered, which is why a heap is cheaper to keep up than a sorted list. The heapq module works on plain lists:
| Function | Cost | Does |
|---|---|---|
heapify(lst) |
rearranges a list into a heap, in place | |
heappush(h, x) |
adds x |
|
heappop(h) |
removes and returns the smallest | |
heappushpop(h, x) |
pushes x, then pops the smallest |
|
heapreplace(h, x) |
pops the smallest, then pushes x (the heap must not be empty) |
|
h[0] |
peeks at the smallest | |
nlargest(k, it, key=) |
the k largest items, largest first |
|
nsmallest(k, it, key=) |
the k smallest items |
|
merge(*sorted_its) |
for m inputs |
lazily merges sorted iterables |
import heapq
daily_revenue = [4217.61, 3943.0, 6365.2, 5598.75, 4259.1, 5636.4, 4416.8]heap = daily_revenue[:]heapq.heapify(heap)print("smallest:", heap[0])print("heap list:", heap)print("in order:", [heapq.heappop(heap) for _ in range(3)])print("top 2:", heapq.nlargest(2, daily_revenue))smallest: 3943.0heap list: [3943.0, 4217.61, 4416.8, 5598.75, 4259.1, 5636.4, 6365.2]in order: [3943.0, 4217.61, 4259.1]top 2: [6365.2, 5636.4]The heap list is not sorted (5598.75 comes before 4259.1), but each element is at most its children. Each heappop takes the smallest and repairs the heap in .
heapq has only a min-heap in Python 3.12 and 3.13. For a max-heap, push negated numbers (-revenue) and negate again when you pop.
Hash maps: count, group and match in one pass
Section titled “Hash maps: count, group and match in one pass”A Python dict is a hash map (a hash table, module 04): it finds a key in on average. That one fact turns many quadratic loops into linear ones. Three patterns cover most data work:
| Pattern | Question | Tool |
|---|---|---|
| counting | how many lines per channel? | Counter, or d[k] = d.get(k, 0) + 1 |
| grouping | which orders belong to each customer? | defaultdict(list) |
| matching | which earlier value completes this one? | a dict of seen values |
The matching pattern is the classic two-sum problem: find two values that add up to a target. A nested loop tests all pairs. The hash map version walks the list once. For each value it asks: “Have I already seen the complement, target - value?” The dict answers in .
def two_sum(amounts: list[int], target: int) -> tuple[int, int] | None: """Return the indices of two amounts that add up to target, or None.""" seen: dict[int, int] = {} # amount -> index for i, amount in enumerate(amounts): complement = target - amount if complement in seen: return seen[complement], i seen[amount] = i return None
amounts_cents = [6649, 1499, 1999, 5999, 22410, 2999] # 66.49, 14.99, ...print(two_sum(amounts_cents, 8648)) # 66.49 + 19.99print(two_sum(amounts_cents, 100))(0, 2)NoneThe amounts are in whole cents. A sum of floats such as 66.49 + 19.99 may not equal 86.48 exactly (module 01), so an exact dict lookup would fail. Integers are exact.
Two pointers
Section titled “Two pointers”The two pointers pattern walks a sorted sequence with two indices at once. Each step moves one of them, so the whole walk is instead of . Two common forms:
- Same direction: one index reads, the other writes. Use it to remove duplicates from sorted IDs, or to merge two sorted lists.
- Opposite ends: one index starts at the left, one at the right, and they move toward each other. Use it to find a pair with a given sum in sorted data.
Merging two sorted lists is the merge step of merge sort, on its own:
def merge_sorted(a: list[str], b: list[str]) -> list[str]: i = j = 0 out: list[str] = [] while i < len(a) and j < len(b): if a[i] <= b[j]: out.append(a[i]) i += 1 else: out.append(b[j]) j += 1 return out + a[i:] + b[j:]
store_s01 = ["2024-05-01T09:12", "2024-05-01T11:40", "2024-05-01T16:05"]online = ["2024-05-01T08:03", "2024-05-01T12:30"]print(merge_sorted(store_s01, online))['2024-05-01T08:03', '2024-05-01T09:12', '2024-05-01T11:40', '2024-05-01T12:30', '2024-05-01T16:05']Each loop step appends one element and moves one pointer, so merging elements in total takes at most comparisons. heapq.merge() does the same for any number of sorted inputs.
Sliding windows
Section titled “Sliding windows”Module 10 built a sliding window with a generator: a fixed-size view that moves along a sequence one element at a time. As an algorithm pattern, the window is about reuse. When the window moves by one, one element enters and one leaves. You update the result with those two elements instead of recomputing it from scratch.
For a 6-reading rolling sum, recomputing sum(window) costs 6 additions per position. The running version costs 2 (add the new value, subtract the old one), whatever the window size:
A variable-size window grows on the right while a condition holds and shrinks from the left when it breaks. It finds the longest stretch with some property, such as the longest streak of days with growing revenue. Worked example 8 builds both kinds, plus a rolling maximum.
Recursion or iteration
Section titled “Recursion or iteration”A recursive function calls itself on a smaller part of the problem (module 05). Recursion fits data that is recursive itself: trees, nested JSON and divide and conquer algorithms such as merge sort. It has two costs in Python:
- Each call adds a frame to the call stack. Python limits the depth of the stack to protect the program from a crash. This recursion limit is 1,000 frames by default (
sys.getrecursionlimit()). Deeper recursion raisesRecursionError. - A call is slower than a loop step.
Python does not optimize tail calls (a recursive call that is the last action of the function), so every recursive function that goes deep needs a rewrite as a loop. The rewrite keeps its own stack in a list.
import sys
print(sys.getrecursionlimit())
def chain_depth(node: dict) -> int: """Depth of a nested {"child": {...}} chain, recursively.""" return 0 if not node else 1 + chain_depth(node["child"])
def build_chain(levels: int) -> dict: root: dict = {} node = root for _ in range(levels): node["child"] = {} node = node["child"] return root
print(chain_depth(build_chain(50)))100050print(chain_depth(build_chain(5_000)))RecursionError: maximum recursion depth exceededThe iterative version walks the chain with a loop and has no depth limit:
def chain_depth_iter(node: dict) -> int: depth = 0 while node: depth += 1 node = node["child"] return depth
print(chain_depth_iter(build_chain(5_000)))5000sys.setrecursionlimit(n) raises the limit, but a much higher limit can crash the interpreter itself when its C stack runs out. Prefer a loop for deep data.
The other trap of recursion is repeated work. Say a warehouse robot picks 1, 2 or 3 units per trip. How many different trip sequences fill an order of units? The last trip is 1, 2 or 3 units, so ways(n) = ways(n - 1) + ways(n - 2) + ways(n - 3). The plain recursion solves the same smaller problems again and again. These repeats are overlapping subproblems, and they make the call count grow exponentially. Exponential time, for some , multiplies the work by a constant each time grows by one. Memoization (module 09, functools.cache) stores each answer the first time and reuses it:
from functools import cache
calls = {"plain": 0, "memo": 0}
def ways(n: int) -> int: calls["plain"] += 1 if n < 0: return 0 if n == 0: return 1 return ways(n - 1) + ways(n - 2) + ways(n - 3)
@cachedef ways_memo(n: int) -> int: calls["memo"] += 1 if n < 0: return 0 if n == 0: return 1 return ways_memo(n - 1) + ways_memo(n - 2) + ways_memo(n - 3)
print(ways(20), ways_memo(20), calls)121415 121415 {'plain': 433993, 'memo': 23}Both give 121,415 sequences. The plain version makes 433,993 calls; the memoized one makes 23, one per distinct value of n from 20 down to −2. Memoization turned exponential time into linear time. Solving a problem from stored answers of its overlapping subproblems is called dynamic programming.
Worked examples
Section titled “Worked examples”Example 1 — Find the first sensor reading after a time
Section titled “Example 1 — Find the first sensor reading after a time”Goal: A technician reports a fault at 2024-05-03 14:05. Find the first reading of sensor S1 at or after that time in data/sensors.csv, then answer 100 such questions, and compare the work of linear search, binary search and bisect.
Step 1 — Load the timestamps of S1
Section titled “Step 1 — Load the timestamps of S1”import csv
with open("data/sensors.csv", newline="") as f: s1 = [row for row in csv.DictReader(f) if row["sensor_id"] == "S1"]
times = [row["timestamp"] for row in s1]print(len(times), times[0], times[-1])print("sorted:", times == sorted(times))2016 2024-05-01T00:00:00 2024-05-14T23:50:00sorted: TrueS1 has 2,016 readings. The file is sorted by timestamp, and the check confirms it. Always confirm the precondition: binary search on unsorted data returns wrong answers without any error.
Step 2 — Search linearly and count the comparisons
Section titled “Step 2 — Search linearly and count the comparisons”def first_at_or_after_linear(times: list[str], target: str) -> tuple[int, int]: comparisons = 0 for i, t in enumerate(times): comparisons += 1 if t >= target: return i, comparisons return len(times), comparisons
fault = "2024-05-03T14:05:00"i, steps = first_at_or_after_linear(times, fault)print(i, times[i], s1[i]["temperature_c"], "comparisons:", steps)373 2024-05-03T14:10:00 24.56 comparisons: 374The first reading after the fault is at 14:10, index 373. The scan compared 374 timestamps to get there. A fault near the end of the two weeks would cost about 2,000.
Step 3 — Search with a hand-written binary search
Section titled “Step 3 — Search with a hand-written binary search”def first_at_or_after_binary(times: list[str], target: str) -> tuple[int, int]: lo, hi = 0, len(times) comparisons = 0 while lo < hi: mid = (lo + hi) // 2 comparisons += 1 if times[mid] < target: lo = mid + 1 else: hi = mid return lo, comparisons
print(first_at_or_after_binary(times, fault))print(first_at_or_after_binary(times, "2024-05-14T23:55:00")) # after the last(373, 11)(2016, 10)Same index, 11 comparisons instead of 374. A time after the last reading returns len(times), 2016: “insert at the end”. Your code must check i < len(times) before it reads times[i].
Step 4 — Use bisect_left
Section titled “Step 4 — Use bisect_left”from bisect import bisect_left
i = bisect_left(times, fault)print(i, times[i])373 2024-05-03T14:10:00bisect_left gives the same insertion point as the hand-written version, in one line and in C. Write your own binary search only when bisect cannot express the question, for example to search on a computed condition.
Step 5 — Answer 100 questions
Section titled “Step 5 — Answer 100 questions”import random
rng = random.Random(42)queries = [rng.choice(times) for _ in range(100)]linear_total = sum(first_at_or_after_linear(times, q)[1] for q in queries)binary_total = sum(first_at_or_after_binary(times, q)[1] for q in queries)print(f"linear: {linear_total:,} comparisons, binary: {binary_total:,} comparisons")print(f"ratio: {linear_total / binary_total:.0f}x")linear: 90,506 comparisons, binary: 1,097 comparisonsratio: 83xA linear search looked at about 905 readings per question: on average, about half of the data. Binary search looked at about 11. The gap grows with the data: for a year of readings (52,560), binary search needs 16 comparisons per question.
Common mistakes:
- Running binary search on unsorted data. It returns an index silently. Check
data == sorted(data)once, or sort first. - Reading
times[i]without the checki < len(times). A target after the last element gives anIndexError. - Comparing timestamps in a format that does not sort as text, such as
03/05/2024 14:05. Convert to ISO format or todatetimeobjects first (module 09).
Example 2 — Bucket house prices into price bands
Section titled “Example 2 — Bucket house prices into price bands”Goal: A real estate dashboard shows how many of the 3,000 sales in data/houses.csv fall into five price bands, answers “how many houses sold between two prices?” and keeps a sorted price list as new sales come in.
Step 1 — Load the prices
Section titled “Step 1 — Load the prices”with open("data/houses.csv", newline="") as f: houses = list(csv.DictReader(f))
prices = [int(h["price"]) for h in houses]print(len(prices), min(prices), max(prices))3000 117500 3730500prices now holds 3,000 integers. This replaces the short prices list of the Concepts section.
Step 2 — Map each price to a band with bisect_right
Section titled “Step 2 — Map each price to a band with bisect_right”from bisect import bisect_rightfrom collections import Counter
cuts = [250_000, 400_000, 600_000, 1_000_000] # band edgeslabels = ["under 250k", "250k-400k", "400k-600k", "600k-1M", "1M and up"]
print(labels[bisect_right(cuts, 249_999)], "|", labels[bisect_right(cuts, 250_000)])band_counts = Counter(labels[bisect_right(cuts, p)] for p in prices)for label in labels: print(f"{label:<11} {band_counts[label]:>5}")under 250k | 250k-400kunder 250k 518250k-400k 1116400k-600k 718600k-1M 4591M and up 189bisect_right(cuts, p) counts the cut points that are less than or equal to p. That count is the band index. A price exactly on a cut, 250,000, goes to the higher band. Use bisect_left if a price on the edge belongs to the lower band. This replaces a chain of if/elif tests, and it stays one line when you add bands.
Step 3 — Count the houses in a price range
Section titled “Step 3 — Count the houses in a price range”sorted_prices = sorted(prices)
def count_between(sorted_values: list[int], low: int, high: int) -> int: """Number of values with low <= value <= high.""" return bisect_right(sorted_values, high) - bisect_left(sorted_values, low)
print(count_between(sorted_prices, 300_000, 450_000))print(count_between(sorted_prices, 1_000_000, 10_000_000))check = sum(1 for p in prices if 300_000 <= p <= 450_000)print("check with a scan:", check)957189check with a scan: 957Sort once (), then each range question costs two binary searches (). The scan gives the same answer but reads all 3,000 prices for every question. A dashboard that answers many filter clicks wants the sorted version.
Step 4 — Insert new sales and keep the median current
Section titled “Step 4 — Insert new sales and keep the median current”from bisect import insort
for new_price in [376_000, 1_250_000, 199_500]: insort(sorted_prices, new_price)
def median_sorted(values: list[int]) -> float: n = len(values) mid = n // 2 return values[mid] if n % 2 else (values[mid - 1] + values[mid]) / 2
print(len(sorted_prices), sorted_prices[:3], median_sorted(sorted_prices))print(sorted_prices == sorted(sorted_prices))3003 [117500, 120000, 129000] 376000Trueinsort puts each new price in its place, so the list stays sorted. The median of a sorted list is one index lookup: the middle element for an odd count, the mean of the two middle elements for an even count. No new sort is needed after each sale.
Common mistakes:
- Using
bisect_leftwhere the edge belongs to the upper band, or the reverse. Decide the rule for a value on the edge and test it, as Step 2 does with 249,999 and 250,000. - Calling
bisecton the unsortedpriceslist. Sort first. - Using
insortfor a large batch. Each insert shifts the list. For 10,000 new rows, useextend()and then onesort().
Example 3 — Sort sales records by several keys
Section titled “Example 3 — Sort sales records by several keys”Goal: A regional manager wants the first 12 lines of data/sales.csv ordered by region, then by revenue from high to low, with the order id as a final tie-break. Then you sort 2,000 revenues with a hand-written merge sort and compare its comparisons with sorted().
Step 1 — Load the lines and convert the numbers
Section titled “Step 1 — Load the lines and convert the numbers”with open("data/sales.csv", newline="") as f: sales = list(csv.DictReader(f))
for row in sales: row["revenue"] = float(row["revenue"]) row["quantity"] = int(row["quantity"])
first_12 = sales[:12]print(len(sales), first_12[0]["order_id"], first_12[0]["revenue"])20228 O000001 66.49The CSV module reads every field as text. Text revenues sort wrongly: "2183.1" < "224.1" is True, because text compares character by character. Convert before you sort.
Step 2 — Sort with a tuple key
Section titled “Step 2 — Sort with a tuple key”ranked = sorted(first_12, key=lambda r: (r["region"], -r["revenue"], r["order_id"]))for r in ranked: print(f"{r['region']:<6} {r['revenue']:>8.2f} {r['order_id']} {r['product']}")East 2183.10 O000006 14-inch Ultrabook LaptopEast 116.96 O000005 Chef's Knife SetEast 29.99 O000005 Weeknight Kitchen CookbookSouth 19.99 O000003 Organic Cotton T-ShirtWest 224.10 O000004 Noise-Cancelling HeadphonesWest 179.00 O000009 Merino Wool SweaterWest 119.00 O000008 Waterproof Rain JacketWest 66.49 O000001 Cotton Bed Sheet SetWest 59.99 O000004 Slim Fit JeansWest 21.50 O000007 Shampoo and Conditioner SetWest 16.99 O000009 Harbor Lane MysteriesWest 14.99 O000002 Running Socks 3-PackThe key returns a tuple per line. Python compares the region first, then the negated revenue (so high revenue comes first), then the order id. One sort, three rules.
Step 3 — Get the same order with stable passes
Section titled “Step 3 — Get the same order with stable passes”from operator import itemgetter
passes = sorted(first_12, key=itemgetter("order_id")) # last tie-break firstpasses = sorted(passes, key=itemgetter("revenue"), reverse=True)passes = sorted(passes, key=itemgetter("region")) # main key lastprint(passes == ranked)TrueStable passes run from the least important key to the most important one. Each pass keeps the order of the previous pass among its ties. Use passes when a text key must run in reverse order, which a negation cannot express.
Step 4 — Sort 2,000 revenues with merge sort and with sorted()
Section titled “Step 4 — Sort 2,000 revenues with merge sort and with sorted()”revenues = [r["revenue"] for r in sales[:2000]]counter = [0]by_merge = merge_sort(revenues, counter)print(by_merge == sorted(revenues))print("merge sort:", counter[0], "| Timsort:", count_sort_comparisons(revenues))shuffled_revenues = revenues[:]random.Random(42).shuffle(shuffled_revenues)print("Timsort on a shuffled copy:", count_sort_comparisons(shuffled_revenues))print("n log2 n:", round(2000 * math.log2(2000)))Truemerge sort: 19433 | Timsort: 18903Timsort on a shuffled copy: 18759n log2 n: 21932Both sorts give the same list, and both stay below . Timsort makes fewer comparisons than merge sort. The order of the sales data is not the reason: the shuffled copy costs about the same. Timsort sorts short stretches with binary insertion sort, which needs few comparisons per element. Its merges also gallop: when one side wins many times in a row, Timsort jumps ahead with a binary search instead of comparing element by element.
Common mistakes:
- Sorting numbers that are still text.
sorted(["2183.1", "224.1", "66.49"])puts 2183.1 first. Convert withfloat(). - Writing
-r["region"]to reverse a text key. It raisesTypeError: bad operand type for unary -: 'str'. Use stable passes orreverse=Trueon that pass. - Writing
sales = sales.sort(...).list.sort()returnsNone, so you lose the list. Usesales.sort(...)alone, orsorted().
Example 4 — Check brackets in config text and undo cleaning steps
Section titled “Example 4 — Check brackets in config text and undo cleaning steps”Goal: A pipeline reads its settings from JSON text. Before it parses the text, a pre-commit check reports the exact position of an unbalanced bracket in data/config.json, and a cleaning session supports undo.
Step 1 — Read the config as text
Section titled “Step 1 — Read the config as text”from pathlib import Path
config_text = Path("data/config.json").read_text(encoding="utf-8")print(len(config_text.splitlines()), "lines")print(sum(config_text.count(c) for c in "{["), "openers,", sum(config_text.count(c) for c in "}]"), "closers")73 lines14 openers, 14 closersEqual counts are not enough: }{ has one of each and is still wrong. The order matters, and a stack checks the order.
Step 2 — Match brackets with a stack
Section titled “Step 2 — Match brackets with a stack”PAIRS = {")": "(", "]": "[", "}": "{"}
def check_brackets(text: str) -> str: stack: list[tuple[str, int, int]] = [] # (bracket, line, column) for line_no, line in enumerate(text.splitlines(), start=1): for col, char in enumerate(line, start=1): if char in "([{": stack.append((char, line_no, col)) elif char in PAIRS: if not stack or stack[-1][0] != PAIRS[char]: return f"unexpected {char!r} at line {line_no}, column {col}" stack.pop() if stack: char, line_no, col = stack[-1] return f"{char!r} opened at line {line_no}, column {col} is never closed" return "balanced"
print(check_brackets(config_text))balancedEach opener is pushed with its position. Each closer must match the opener on top of the stack, which is the most recent one still open. At the end, the stack must be empty. The check is for characters. It does not skip brackets inside quoted strings; this config has none. Exercise M17-C07 adds that.
Step 3 — Break the config and locate the error
Section titled “Step 3 — Break the config and locate the error”broken = config_text.replace('"overwrite": false\n }', '"overwrite": false\n ]', 1)print(check_brackets(broken))print(check_brackets('}{"retry": 3}'))print(check_brackets('{"model": {"params": {"C": 1.0}'))unexpected ']' at line 15, column 3unexpected '}' at line 1, column 1'{' opened at line 1, column 11 is never closedThe three messages cover the three failure kinds: a closer that does not match the opener on top of the stack (] arrives while { is open), a closer with nothing open, and an opener that is never closed. json.loads also fails on all three. For the first two, it reports the same position, but only as Expecting ',' delimiter or similar; the checker names the bracket. For the unclosed opener, json.loads points at the end of the text, while the checker points at the bracket that was never closed.
Step 4 — Undo cleaning steps with a stack
Section titled “Step 4 — Undo cleaning steps with a stack”prices_raw = ["$79.99", " $249.00", "N/A", "$1,299.00 "]history: list[list[str]] = []steps = [ ("strip", str.strip), ("remove $ and ,", lambda p: p.replace("$", "").replace(",", "")), ("lowercase", str.lower), # a mistake: it changes N/A to n/a]for name, func in steps: history.append(prices_raw) # push the state before the step prices_raw = [func(p) for p in prices_raw] print(f"{name:<14} -> {prices_raw}")
prices_raw = history.pop() # undo the last stepprint("after undo ->", prices_raw, "| steps left to undo:", len(history))strip -> ['$79.99', '$249.00', 'N/A', '$1,299.00']remove $ and , -> ['79.99', '249.00', 'N/A', '1299.00']lowercase -> ['79.99', '249.00', 'n/a', '1299.00']after undo -> ['79.99', '249.00', 'N/A', '1299.00'] | steps left to undo: 2Each step pushes the old state before it changes anything. Undo pops the most recent state, so repeated undos walk back in reverse order. A redo feature would push the undone state onto a second stack. The steps build new lists, so each snapshot stays unchanged.
Common mistakes:
- Counting brackets instead of matching them.
}{passes a count check. - Popping from an empty stack.
[].pop()raisesIndexError. Checkif not stackfirst, as Step 2 does. - Pushing a reference to a list that you then change in place. Every snapshot would show the final state. Push a copy, or build a new list in each step.
Example 5 — Walk a product category tree
Section titled “Example 5 — Walk a product category tree”Goal: The shop’s catalog is a tree: root, departments, subcategories and products from data/products.csv. List the nodes level by level, find the depth of each product, and count the products under each node, recursively and iteratively.
Step 1 — Store the tree as an adjacency list
Section titled “Step 1 — Store the tree as an adjacency list”catalog = { "All products": ["Electronics", "Home", "Sports"], "Electronics": ["Audio", "Computers", "Wearables"], "Audio": ["Wireless Earbuds", "Noise-Cancelling Headphones"], "Computers": ["14-inch Ultrabook Laptop"], "Wearables": ["Smartwatch Series 5", "Fitness Tracker"], "Home": ["Kitchen", "Cleaning"], "Kitchen": ["Espresso Machine", "Chef's Knife Set"], "Cleaning": ["Robot Vacuum"], "Sports": ["Non-Slip Yoga Mat", "Trail Running Shoes"],}nodes = set(catalog) | {child for kids in catalog.values() for child in kids}leaves = sorted(n for n in nodes if n not in catalog)print(len(nodes), "nodes,", len(leaves), "leaves")19 nodes, 10 leavesThe dict maps each node to its children. A node that is not a key has no children, so it is a leaf: a product.
Step 2 — Visit the levels with BFS
Section titled “Step 2 — Visit the levels with BFS”def bfs_levels(tree: dict[str, list[str]], root: str) -> dict[str, int]: """Return the depth of every node, in the order BFS visits them.""" depth = {root: 0} queue = deque([root]) while queue: node = queue.popleft() # FIFO: the oldest waiting node for child in tree.get(node, []): depth[child] = depth[node] + 1 queue.append(child) return depth
depth = bfs_levels(catalog, "All products")for level in range(max(depth.values()) + 1): names = [n for n, d in depth.items() if d == level] shown = ", ".join(names[:3]) + (", ..." if len(names) > 3 else "") print(f"level {level} ({len(names)}): {shown}")print("depth of Robot Vacuum:", depth["Robot Vacuum"])print("depth of Yoga Mat:", depth["Non-Slip Yoga Mat"])level 0 (1): All productslevel 1 (3): Electronics, Home, Sportslevel 2 (7): Audio, Computers, Wearables, ...level 3 (8): Wireless Earbuds, Noise-Cancelling Headphones, 14-inch Ultrabook Laptop, ...depth of Robot Vacuum: 3depth of Yoga Mat: 2BFS takes nodes from the front of the queue and adds children at the back, so it finishes a whole level before it starts the next one. Each node enters and leaves the queue once: . The sports products sit one level higher, because the Sports department has no subcategories.
Step 3 — Count products under each node with recursive DFS
Section titled “Step 3 — Count products under each node with recursive DFS”def count_products(tree: dict[str, list[str]], node: str) -> int: children = tree.get(node, []) if not children: # base case: a leaf is one product return 1 return sum(count_products(tree, child) for child in children)
for node in ["All products", "Electronics", "Home", "Audio"]: print(f"{node:<13} {count_products(catalog, node)}")All products 10Electronics 5Home 3Audio 2The recursion goes deep first: it finishes the whole Electronics branch before it touches Home. The tree has 3 levels below the root, so the recursion is never deeper than 4 calls, far below the limit of 1,000.
Step 4 — Do the same DFS with an explicit stack
Section titled “Step 4 — Do the same DFS with an explicit stack”def count_products_iter(tree: dict[str, list[str]], root: str) -> int: total = 0 stack = [root] while stack: node = stack.pop() # LIFO: the newest node, so we go deep first children = tree.get(node, []) if children: stack.extend(children) else: total += 1 return total
print(count_products_iter(catalog, "All products"))print(all(count_products_iter(catalog, n) == count_products(catalog, n) for n in nodes))10TrueThe only difference between this DFS and the BFS of Step 2 is the end where nodes leave: pop() from a stack instead of popleft() from a queue. The explicit stack lives in a list, so a tree thousands of levels deep works too.
Common mistakes:
- Using
list.pop(0)as the queue in BFS. The result is right, but every pop shifts the list: on a large tree. Usedeque.popleft(). - Running BFS or DFS on a graph with loops and no
visitedset. The walk never ends. A tree has no loops; a graph needsif child not in visited. - Forgetting the base case of the recursion. Python raises
RecursionErrorafter 1,000 calls.
Example 6 — Rank products by revenue with heapq
Section titled “Example 6 — Rank products by revenue with heapq”Goal: Find the top 3 of the 30 products by total revenue in data/sales.csv, keep a top 5 of single sales lines while the lines stream in, merge sorted order streams from three stores and run a priority queue of pipeline tasks.
Step 1 — Total the revenue per product with a hash map
Section titled “Step 1 — Total the revenue per product with a hash map”from collections import defaultdict
revenue_by_product: dict[str, float] = defaultdict(float)for row in sales: revenue_by_product[row["product"]] += row["revenue"]
print(len(revenue_by_product), "products")print(round(revenue_by_product["Wireless Earbuds"], 2))30 products120248.5One pass over 20,228 lines builds 30 totals. Each += on the dict is on average.
Step 2 — Take the top 3 with nlargest
Section titled “Step 2 — Take the top 3 with nlargest”top_3 = heapq.nlargest(3, revenue_by_product.items(), key=itemgetter(1))for product, total in top_3: print(f"{product:<28} {total:>12,.2f}")14-inch Ultrabook Laptop 665,328.4555-inch 4K Smart TV 628,586.10Noise-Cancelling Headphones 231,943.50nlargest(k, items, key=...) keeps only k candidates in a heap while it reads the items: . A full sorted(..., reverse=True)[:3] is . With 30 products both are instant. With millions of rows and , the heap does far less work and uses memory. When k is close to n, sort instead.
Step 3 — Keep a top 5 of sales lines while they stream in
Section titled “Step 3 — Keep a top 5 of sales lines while they stream in”top_lines: list[tuple[float, str]] = [] # a min-heap of the best 5 so farpushes = 0for row in sales: item = (row["revenue"], row["order_id"]) if len(top_lines) < 5: heapq.heappush(top_lines, item) pushes += 1 elif item > top_lines[0]: # better than the worst of the top 5 heapq.heapreplace(top_lines, item) # pop the smallest, push item pushes += 1
for revenue, order_id in sorted(top_lines, reverse=True): print(order_id, f"{revenue:,.2f}")print("heap updates:", pushes, "of", len(sales), "lines")O001531 5,196.00O014369 4,596.00O011849 4,596.00O006934 4,596.00O006473 4,366.20heap updates: 61 of 20228 linesThe heap’s smallest element, top_lines[0], is the weakest member of the top 5. A new line enters only when it beats that one. Most lines are cheap and never touch the heap: only 61 of 20,228 lines caused an update. Three lines tie at 4,596.00, and the order id breaks the tie. The tuples compare by revenue first and break ties by order id.
Step 4 — Merge sorted streams from three stores
Section titled “Step 4 — Merge sorted streams from three stores”from collections.abc import Iterator
def store_stream(store_id: str) -> Iterator[tuple[str, str, str]]: """Yield (date, order_id, store_id) of one store's lines, in date order.""" for row in sales: if row["store_id"] == store_id: yield row["order_date"], row["order_id"], store_id
merged = heapq.merge(store_stream("S01"), store_stream("S07"), store_stream("S12"))first_5 = [next(merged) for _ in range(5)]for item in first_5: print(item)('2023-01-01', 'O000006', 'S07')('2023-01-01', 'O000012', 'S01')('2023-01-01', 'O000012', 'S01')('2023-01-01', 'O000015', 'S01')('2023-01-01', 'O000015', 'S01')heapq.merge keeps one item per input in a small heap and always yields the smallest. It is lazy: it reads only as far as you ask, so it merges files that do not fit in memory. Each input must already be sorted; merge does not check this. Orders O000012 and O000015 appear twice, because each one has two lines at store S01.
Step 5 — Run a priority queue of pipeline tasks
Section titled “Step 5 — Run a priority queue of pipeline tasks”from itertools import count
tasks: list[tuple[int, int, str]] = []arrival = count() # 0, 1, 2, ...: a tie-breaker that keeps arrival orderfor priority, name in [(2, "refresh dashboard"), (0, "fix failed load"), (1, "retrain churn model"), (0, "rotate API key")]: heapq.heappush(tasks, (priority, next(arrival), name))
while tasks: priority, _, name = heapq.heappop(tasks) print(priority, name)0 fix failed load0 rotate API key1 retrain churn model2 refresh dashboardLower numbers mean more urgent. The two priority-0 tasks come out in arrival order, because the counter breaks the tie. Without the counter, a tie would compare the names, and with objects that cannot be compared (such as dicts), Python would raise TypeError.
Common mistakes:
- Expecting a heap list to be sorted. Only
heap[0]is guaranteed. Pop the items, or callsorted(heap). - Pushing
(priority, task_dict)tuples. Two equal priorities make Python compare the dicts:TypeError: '<' not supported between instances of 'dict' and 'dict'. Add a counter as the second element. - Using
heappushandheappopon a list that was never heapified. The functions assume the heap property and give wrong answers otherwise. Callheapify()first, or start from an empty list.
Example 7 — Match transactions with a hash map and two pointers
Section titled “Example 7 — Match transactions with a hash map and two pointers”Goal: A card issuer flags a disputed charge. The merchant says the amount was the sum of two of the day’s sales lines. Find the two lines in the 2023-11-24 (Black Friday) sales, compare the work of the brute-force, hash map and two-pointer solutions, and remove repeated customer ids from a sorted list.
Step 1 — Get the day’s amounts in cents
Section titled “Step 1 — Get the day’s amounts in cents”day = [row for row in sales if row["order_date"] == "2023-11-24"]cents = [round(row["revenue"] * 100) for row in day]print(len(day), "lines; first amounts:", cents[:5])disputed = cents[10] + cents[100] # a known pair, so the search must succeedprint("disputed amount:", disputed / 100)127 lines; first amounts: [17955, 10796, 1349, 5599, 3149]disputed amount: 184.08round(revenue * 100) turns 179.55 into the integer 17955. The disputed amount is built from lines 10 and 100, so you know a match exists. In real use it comes from the issuer.
Step 2 — Try every pair (brute force)
Section titled “Step 2 — Try every pair (brute force)”Pair = tuple[int, int]
def two_sum_brute(amounts: list[int], target: int) -> tuple[Pair | None, int]: checks = 0 for i in range(len(amounts)): for j in range(i + 1, len(amounts)): checks += 1 if amounts[i] + amounts[j] == target: return (i, j), checks return None, checks
pair, checks = two_sum_brute(cents, disputed)print(pair, [cents[k] for k in pair], "checks:", checks)print("all pairs:", len(cents) * (len(cents) - 1) // 2)(8, 100) [13998, 4410] checks: 1072all pairs: 8001The brute force stops at the first match: lines 8 and 100, not the known pair 10 and 100. Line 8 has the same amount as line 10 (139.98), so both pairs are candidates. It needed 1,072 checks to get there. When no pair matches, it checks all 8,001 pairs: .
Step 3 — Find all matching pairs with a hash map
Section titled “Step 3 — Find all matching pairs with a hash map”def all_pairs_hash(amounts: list[int], target: int) -> tuple[list[Pair], int]: seen: dict[int, list[int]] = defaultdict(list) # amount -> indices pairs: list[Pair] = [] lookups = 0 for j, amount in enumerate(amounts): lookups += 1 for i in seen.get(target - amount, []): pairs.append((i, j)) seen[amount].append(j) return pairs, lookups
pairs, lookups = all_pairs_hash(cents, disputed)print(len(pairs), "candidate pairs,", lookups, "lookups")print("known pair found:", (10, 100) in pairs)print("distinct amount pairs:", sorted({(cents[i], cents[j]) for i, j in pairs}))2 candidate pairs, 127 lookupsknown pair found: Truedistinct amount pairs: [(13998, 4410)]One pass, one dict lookup per line: 127 lookups, where the brute force needs up to 8,001 checks. The dict stores a list of indices per amount, because the same price appears on many lines. So the function finds every candidate pair, here both (8, 100) and (10, 100). The investigator now knows the charge was 139.98 + 44.10, and that two sales lines could be the 139.98 part.
Step 4 — Find a pair with two pointers on sorted amounts
Section titled “Step 4 — Find a pair with two pointers on sorted amounts”def two_sum_sorted(values: list[int], target: int) -> tuple[Pair | None, int]: left, right = 0, len(values) - 1 steps = 0 while left < right: steps += 1 total = values[left] + values[right] if total == target: return (values[left], values[right]), steps if total < target: left += 1 # need a bigger sum else: right -= 1 # need a smaller sum return None, steps
sorted_cents = sorted(cents)print(two_sum_sorted(sorted_cents, disputed))print(two_sum_sorted(sorted_cents, 1))((4410, 13998), 90)(None, 126)On sorted data, the smallest plus the largest tells you which pointer to move. If the sum is too small, only a bigger left value can help; if it is too large, only a smaller right value can help. Each step moves one pointer, so at most steps. It needs the sort () but no extra dict, so it suits data that is already sorted.
Step 5 — Remove repeated ids from a sorted list in place
Section titled “Step 5 — Remove repeated ids from a sorted list in place”ids = sorted(row["customer_id"] for row in day)print(len(ids), ids[:6])
write = 1 # ids[:write] holds the distinct ids found so farfor read in range(1, len(ids)): if ids[read] != ids[write - 1]: ids[write] = ids[read] write += 1del ids[write:]print(len(ids), ids[:4], len(ids) == len(set(row["customer_id"] for row in day)))127 ['C00007', 'C00073', 'C00130', 'C00181', 'C00216', 'C00227']89 ['C00007', 'C00073', 'C00130', 'C00181'] TrueThe read pointer visits every id; the write pointer moves only for a new id. In sorted data, repeats sit next to each other, so comparing with the last written id is enough. The list shrinks in place with extra memory. sorted(set(ids)) is shorter and fine for most work; the pointer version matters when memory is tight or when the data is a stream.
Common mistakes:
- Matching float amounts with a dict.
0.1 + 0.2is not0.3, so the lookup fails. Convert to integer cents. - Storing one index per amount (
seen[amount] = i) when you need every pair. Repeated amounts overwrite each other. - Running two pointers on unsorted data. The moves rely on the order, so the search misses pairs.
Example 8 — Rolling statistics and growth streaks
Section titled “Example 8 — Rolling statistics and growth streaks”Goal: Compute a rolling mean and a rolling maximum of the vibration of sensor S4 over windows of 6 readings (one hour), count the work of each method, and find the longest streak of growing daily revenue in data/sales.csv.
Step 1 — Load the S4 vibration readings
Section titled “Step 1 — Load the S4 vibration readings”with open("data/sensors.csv", newline="") as f: s4 = [ (row["timestamp"], float(row["vibration_mm_s"])) for row in csv.DictReader(f) if row["sensor_id"] == "S4" and row["vibration_mm_s"] ]vibration = [v for _, v in s4]print(len(vibration), vibration[:6])2009 [2.17, 2.42, 3.17, 3.83, 2.67, 2.79]Seven readings are blank and are skipped. The rest stay in time order.
Step 2 — Compute the rolling mean with a running sum
Section titled “Step 2 — Compute the rolling mean with a running sum”K = 6
def rolling_mean(values: list[float], k: int) -> tuple[list[float], int]: ops = 0 window_sum = sum(values[:k]) ops += k means = [window_sum / k] for i in range(k, len(values)): window_sum += values[i] - values[i - k] # one in, one out ops += 2 means.append(window_sum / k) return means, ops
means, ops = rolling_mean(vibration, K)naive_ops = (len(vibration) - K + 1) * Kprint(len(means), round(means[0], 3), round(max(means), 3))print("running sum ops:", ops, "| recompute ops:", naive_ops)2004 2.842 10.53running sum ops: 4012 | recompute ops: 12024There are windows. The running sum does 2 operations per move; recomputing does 6. For a window of 144 readings (one day), recomputing would cost 72 times as much. A running sum of floats collects tiny rounding errors over millions of steps; recompute it from scratch now and then if you need exact values.
Step 3 — Compute the rolling maximum with a monotonic deque
Section titled “Step 3 — Compute the rolling maximum with a monotonic deque”A sum can subtract the value that leaves the window. A maximum cannot: when the largest value leaves, you do not know the next largest. A monotonic deque solves this. It stores indices whose values decrease from front to back. The front is always the maximum of the window.
def rolling_max(values: list[float], k: int) -> tuple[list[float], int]: window: deque[int] = deque() # indices; their values decrease maxima: list[float] = [] ops = 0 for i, value in enumerate(values): while window and values[window[-1]] <= value: window.pop() # smaller older values can never be the max again ops += 1 window.append(i) ops += 1 if window[0] <= i - k: window.popleft() # the front index has left the window ops += 1 if i >= k - 1: maxima.append(values[window[0]]) return maxima, ops
maxima, ops = rolling_max(vibration, K)check = [max(vibration[i : i + K]) for i in range(len(vibration) - K + 1)]print(maxima == check, len(maxima), max(maxima))print("deque ops:", ops, "| recompute ops:", len(check) * K)True 2004 18.98deque ops: 4016 | recompute ops: 12024Each index enters the deque once and leaves it at most once, so the total work is at most , whatever the window size. Recomputing max() over each window costs per position. The check against the simple version passes.
Step 4 — Alert on windows above the warning level
Section titled “Step 4 — Alert on windows above the warning level”alerts = [s4[i + K - 1][0] for i, m in enumerate(means) if m >= 4.5]print(len(alerts), "windows with mean >= 4.5 mm/s")print("from May 12 on:", sum(1 for ts in alerts if ts >= "2024-05-12"))print("first:", alerts[0], "| last:", alerts[-1])440 windows with mean >= 4.5 mm/sfrom May 12 on: 397first: 2024-05-01T08:00:00 | last: 2024-05-14T23:40:00The status rule of the dataset warns at 4.5 mm/s. 397 of the 440 alert windows fall in the last three days, when the wear of S4 begins. The earlier ones come from single vibration spikes. One reading of 12.9 to 17.7 mm/s lifts the mean of each of the 6 windows that contain it above 4.5, so a mean-based alarm still fires on one bad reading. Each alert carries the timestamp of the last reading in its window. The text comparison ts >= "2024-05-12" works because ISO timestamps sort as text.
Step 5 — Find the longest streak of growing daily revenue
Section titled “Step 5 — Find the longest streak of growing daily revenue”daily: dict[str, float] = defaultdict(float)for row in sales: daily[row["order_date"]] += row["revenue"]days = sorted(daily)
best_len, best_end = 1, 0run_start = 0 # left edge of the current windowfor i in range(1, len(days)): if daily[days[i]] <= daily[days[i - 1]]: run_start = i # growth broke: shrink the window to day i alone if i - run_start + 1 > best_len: best_len, best_end = i - run_start + 1, i
streak = days[best_end - best_len + 1 : best_end + 1]print(best_len, "days:", streak[0], "to", streak[-1])print([round(daily[d]) for d in streak])8 days: 2023-10-24 to 2023-10-31[509, 2126, 2877, 2982, 3125, 3340, 5823, 6947]This is a variable-size window. It grows by one day while revenue rises and restarts at the day that breaks the rise. One pass over 731 days finds the longest streak: 8 days with 7 rises in a row. Checking every start and end day would be .
Common mistakes:
- Off-by-one window edges. A window of
kvalues that ends at indexistarts ati - k + 1. Test against the simple version, as Step 3 does. - Storing values instead of indices in the monotonic deque. You cannot tell when a value has left the window.
- Counting rises instead of days in a streak. 8 growing days contain 7 rises. Say which one you report.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
Binary search or bisect on unsorted data |
A wrong index, no error | Sort first, or check data == sorted(data) |
times[i] after i = bisect_left(times, t) |
IndexError when t is after the last element |
Check i < len(times) |
bisect_left where the edge belongs to the upper band |
Values on the edge land in the wrong band | Use bisect_right for “edge goes up”, bisect_left for “edge goes down” |
insort in a loop over a big batch |
Slow: each insert shifts the list | extend() then one sort() |
| Sorting numbers stored as text | "2183.1" before "224.1" |
Convert with float() or int() first |
-r["name"] in a key |
TypeError: bad operand type for unary -: 'str' |
Stable passes with reverse=True |
result = lst.sort() |
result is None |
lst.sort() alone, or sorted(lst) |
list.pop(0) as a queue |
Slow on long queues: per pop | deque.popleft() |
Heap of (priority, dict) |
TypeError on equal priorities |
(priority, counter, item) |
| Expecting a heap list to be sorted | Elements after heap[0] look random |
Pop items, or sorted(heap) |
| Float keys in a two-sum dict | Matches are missed | Integer cents |
| Graph walk with no visited set | Infinite loop on a cycle | Track visited |
| Deep recursion on deep data | RecursionError: maximum recursion depth exceeded |
A loop with an explicit stack |
| Plain recursion with overlapping subproblems | Exponential call count | functools.cache, or build the table bottom-up |
| Timing two algorithms once on a busy laptop | Results change from run to run | Count operations, or use timeit with repeats (module 15) |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web development: an API rate limiter keeps the timestamps of recent requests in a
dequeand drops old ones from the left: a sliding window. Routing tables and feature-flag rollouts usebisecton sorted cut points, like the price bands of Example 2. - Systems and tooling:
asynciokeeps its scheduled callbacks in a heap ordered by time, so the next one is alwaysheap[0]. Job schedulers and task queues are priority queues.gitand package managers walk dependency graphs with BFS and DFS. - Editors and apps: undo and redo are two stacks. Code editors and linters match brackets with a stack, as in Example 4.
- Security and finance: fraud checks match a payment to its reversal or to split charges with a hash map, as in Example 7. Log tools merge sorted log files from many servers with a k-way merge, as
heapq.mergedoes.
Summary
Section titled “Summary”- Compare algorithms by counting operations, and describe their growth with big-O: , , , , , exponential.
- Binary search halves the search range at each step: on sorted data.
bisect_left,bisect_rightandinsortdo it for you;bisect_right - bisect_leftcounts a range. sorted()andlist.sort()use Timsort: stable, in the worst case and on data that is already in order. Use tuple keys for several keys and stable passes for mixed directions.- A list is a stack (LIFO); a
dequeis a queue (FIFO). Stacks match brackets, undo steps and drive DFS; queues drive BFS. - A heap keeps the smallest item at index 0 with pushes and pops.
nlargestgives the top k,mergemerges sorted streams, and(priority, counter, item)tuples make a priority queue. - A dict turns counting, grouping and matching (two-sum) into one pass. Two pointers walk sorted data in . Sliding windows reuse the previous window’s result.
- Recursion suits trees and divide and conquer, but Python stops at about 1,000 frames. Use a loop with a list as the stack for deep data, and memoize recursion with overlapping subproblems.
Self-check questions
Section titled “Self-check questions”Q1. Why does this module count operations instead of timing code?
Answer
An operation count is deterministic: it is the same on every machine and in every run. A timing depends on the hardware, other programs and the Python version, so two runs give different numbers. Counts also show the growth directly: double the data and see how the count changes.
Q2. A sorted list has 1,000,000 timestamps. At most how many comparisons does binary search need? And linear search?
Answer
Binary search needs at most comparisons. Linear search needs up to 1,000,000 in the worst case (the target is last or missing).
Q3. prices = [10, 20, 20, 20, 30]. What are bisect_left(prices, 20), bisect_right(prices, 20) and bisect_left(prices, 25)?
Answer
1, 4 and 4. bisect_left returns the index of the first 20 (the gap just before it), bisect_right the position after the last 20, and 25 would go between the last 20 and 30. bisect_right - bisect_left = 3 copies of 20.
Q4. You must sort sales lines by region A to Z and, inside each region, by product name Z to A. Why does a single tuple key not work, and what does?
Answer
The tuple key (region, product) sorts both fields in the same direction, and you cannot negate text to reverse one field. Use two stable passes: first sorted(lines, key=itemgetter("product"), reverse=True), then sort that result by itemgetter("region"). The second pass keeps the product order inside each region.
Q5. Why is sorted() on an already sorted list of 10,000 numbers so much cheaper than on a shuffled one?
Answer
sorted() uses Timsort, which first looks for runs of data that is already in order. A sorted list is one run, so Timsort confirms it with = 9,999 comparisons and stops. A shuffled list has only short runs, so Timsort merges them in about comparisons.
Q6. Which structure do you use for each task, and why: (a) undo in a cleaning tool, (b) processing support tickets in arrival order, (c) always handling the most urgent ticket next?
Answer
(a) A stack (a list with append and pop): undo reverses the most recent step first, LIFO. (b) A queue (deque with append and popleft): first come, first served, FIFO. (c) A priority queue (a heap with heapq, items (priority, counter, ticket)): it pops the smallest priority in .
Q7. What is the only code difference between BFS and DFS with an explicit container, and what does each one find on a graph?
Answer
BFS takes the next node from the front of a queue (popleft()); DFS takes it from the top of a stack (pop()). BFS visits nodes in order of their distance from the start, so it finds the fewest steps to each node. DFS goes deep along one branch first; it is the natural fit for “visit everything below this node”, such as totals per subtree.
Q8. You need the 10 largest of 5,000,000 order revenues. Compare sorted(revenues, reverse=True)[:10] and heapq.nlargest(10, revenues).
Answer
The sort is and builds a full sorted copy of 5 million values. nlargest is with and keeps only 10 values in memory, so it does far less work. Both return the same 10 values, largest first. When k is close to n, sorting is the better choice.
Q9. Why does the hash map version of two-sum take , while the nested loop takes ? What must you do with money amounts?
Answer
The nested loop tests every pair: tests. The hash map version visits each value once and asks the dict for its complement, target - value, which is an lookup on average. So the total is lookups. Money must be in integer cents, because float sums such as 0.1 + 0.2 do not equal the exact target and the lookup would miss.
Q10. A rolling sum over a window of 144 readings recomputes sum(window) at every position. What is the faster method, and how many operations does it need per move?
Answer
A running sum: add the value that enters and subtract the value that leaves, . It needs 2 operations per move, instead of 144.
Q11. A recursive function walks a nested JSON document that is 3,000 levels deep. What happens, and how do you fix it?
Answer
Python raises RecursionError: maximum recursion depth exceeded, because the default recursion limit is 1,000 frames. Rewrite the function as a loop that keeps the nodes still to visit in a list used as a stack. sys.setrecursionlimit() is a risky patch: a very deep recursion can still crash the interpreter.
Q12. The plain recursive ways(20) made 433,993 calls and the memoized version made 23. Explain the difference.
Answer
The plain version solves the same smaller problems many times: ways(17) is computed inside ways(19), ways(18) and ways(20), and each of those calls repeats its own subproblems. These overlapping subproblems make the call count grow exponentially. @cache stores each result the first time, so each n from 20 down to −2 is computed once: 23 calls.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 29 exercises on searching, sorting, stacks, queues, heaps, hash maps, two pointers, sliding windows and recursion.
- Mini-project: build a fast query toolkit for sensor logs and prove its speed with operation counts.
- Cheat sheet: templates for every pattern and a complexity table.
- Part 2 review: the Part 2 checkpoint mixes exercises from modules 10 to 17.
- Next module: 18. Classes and objects starts Part 3. You will wrap data and the algorithms that work on it into your own classes.
- Go deeper later: 45. Algorithms and data structures II adds LRU caches, tries, Union-Find, Dijkstra, DAG topological sort, dynamic programming, Quickselect, KD-trees and Bloom filters.