Skip to content

17. Algorithms and data structures — Exercises

These exercises practice every pattern of the algorithms and data structures lesson. They use the course datasets: data/sensors.csv, data/sales.csv, data/houses.csv, data/products.csv, data/stores.csv, data/sales_raw.csv and data/customers.json.

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block and the starter code into a script, for example exercise.py, and replace each to-do comment with your code.
  3. Run the script with python exercise.py from your project folder (the folder that holds data/). Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Many tasks ask you to count operations: comparisons, lookups or pushes. Add a counter variable to your code and increase it at each step, as the lesson does. Counts are exact, so your counts must match the expected output.

Every exercise below starts from these imports. Put them at the top of each script.

import csv
import heapq
import json
import math
from bisect import bisect_left, bisect_right, insort
from collections import Counter, defaultdict, deque
from collections.abc import Callable
from functools import cache, cmp_to_key
from itertools import islice
from operator import itemgetter
from typing import Any
Section titled “M17-W01 · Count the comparisons of a linear search”
Warm-up

The 30 list prices of data/products.csv are given below, sorted. A marketing team wants the cheapest product that costs at least 100.00. Find it with a linear search: walk the list from the left, count each comparison, and stop at the first price that is 100.00 or more. Print the index, the price and the count.

Expected output
index 18, price 119.0, comparisons 19
Starter
prices = [14.99, 14.99, 15.99, 16.99, 19.99, 21.5, 24.5, 24.99, 29.99, 32.0,
34.99, 34.99, 59.99, 59.99, 69.99, 79.99, 89.5, 99.99, 119.0, 129.95,
129.99, 189.0, 189.99, 199.99, 249.0, 279.0, 299.99, 349.0, 1149.0, 1299.0]
comparisons = 0
# TODO: loop with enumerate, count each comparison, stop at the first price >= 100
Hint 1

for i, price in enumerate(prices): gives you the index and the value. Add 1 to the counter before the if.

Hint 2

Use break to stop the loop when price >= 100. After the loop, i and price still hold the last values.

Solution
prices = [14.99, 14.99, 15.99, 16.99, 19.99, 21.5, 24.5, 24.99, 29.99, 32.0,
34.99, 34.99, 59.99, 59.99, 69.99, 79.99, 89.5, 99.99, 119.0, 129.95,
129.99, 189.0, 189.99, 199.99, 249.0, 279.0, 299.99, 349.0, 1149.0, 1299.0]
comparisons = 0
found = -1
for i, price in enumerate(prices):
comparisons += 1
if price >= 100:
found = i
break
print(f"index {found}, price {prices[found]}, comparisons {comparisons}")
assert prices[found] == 119.0
assert comparisons == found + 1
assert bisect_left(prices, 100) == found
Output
index 18, price 119.0, comparisons 19

How it works:

  1. The loop compares one price per step and counts it.
  2. The first 18 prices are below 100, so the 19th comparison (index 18) succeeds.
  3. A linear search that stops at index i makes i + 1 comparisons. The second assert checks this rule.
  4. The last assert shows that bisect_left finds the same position, because the list is sorted.

Alternative: next(i for i, p in enumerate(prices) if p >= 100) finds the index in one line. It does the same linear scan, but you cannot count the steps.

M17-W02 · Predict the output: bisect on repeated values

Section titled “M17-W02 · Predict the output: bisect on repeated values”
Warm-up

Predict the output: delivery times in days, sorted, contain repeats. Write down what each line prints. Then run the code.

Acceptance criteria:

  • Write your prediction for every line before you run the code.
  • Your prediction matches the Output in the solution, line by line.
  • For each wrong line, you can say which rule of bisect_left or bisect_right you missed.
Starter
days = [1, 2, 2, 2, 3, 5, 5, 8]
print(bisect_left(days, 2), bisect_right(days, 2))
print(bisect_left(days, 4), bisect_right(days, 4))
print(bisect_left(days, 0), bisect_right(days, 9))
print(bisect_right(days, 5) - bisect_left(days, 2))
# TODO: write your prediction for each line before you run it
Hint 1

bisect_left(a, x) is the first index with a[i] >= x. bisect_right(a, x) is the first index with a[i] > x.

Hint 2

For a value that is not in the list, both functions return the same position. The last line counts the values from 2 to 5, inclusive.

Solution
days = [1, 2, 2, 2, 3, 5, 5, 8]
print(bisect_left(days, 2), bisect_right(days, 2))
print(bisect_left(days, 4), bisect_right(days, 4))
print(bisect_left(days, 0), bisect_right(days, 9))
print(bisect_right(days, 5) - bisect_left(days, 2))
assert bisect_right(days, 2) - bisect_left(days, 2) == days.count(2)
assert bisect_right(days, 5) - bisect_left(days, 2) == sum(2 <= d <= 5 for d in days)
Output
1 4
5 5
0 8
6

How it works:

  1. The three 2s sit at indices 1 to 3. bisect_left returns the index of the first 2 (1, the gap just before them), bisect_right the position after the last 2 (4).
  2. 4 is not in the list. It would go between 3 (index 4) and 5 (index 5), so both functions return 5.
  3. 0 is smaller than everything: position 0. 9 is larger than everything: position len(days), 8.
  4. bisect_right(days, 5) is 7 and bisect_left(days, 2) is 1. Their difference, 6, is the number of values from 2 to 5.

Alternative: check any line in the REPL with days[:i] and days[i:]: every value left of a bisect_left position is smaller than x, every value from it on is at least x.

M17-W03 · Insert a late reading with insort

Section titled “M17-W03 · Insert a late reading with insort”
Warm-up

A sensor gateway delivers a delayed reading for 2024-05-01T00:25:00 after the readings below are already stored. Insert it with insort so the list stays sorted by time, and print the position where it landed and the list.

Expected output
inserted at 3
2024-05-01T00:00:00
2024-05-01T00:10:00
2024-05-01T00:20:00
2024-05-01T00:25:00
2024-05-01T00:30:00
2024-05-01T00:40:00
Starter
times = ["2024-05-01T00:00:00", "2024-05-01T00:10:00", "2024-05-01T00:20:00",
"2024-05-01T00:30:00", "2024-05-01T00:40:00"]
late = "2024-05-01T00:25:00"
# TODO: insert late with insort, then print its index and the list
Hint 1

insort(times, late) changes the list in place and returns None.

Hint 2

times.index(late) finds the new position after the insert. bisect_left(times, late) before the insert gives the same number.

Solution
times = ["2024-05-01T00:00:00", "2024-05-01T00:10:00", "2024-05-01T00:20:00",
"2024-05-01T00:30:00", "2024-05-01T00:40:00"]
late = "2024-05-01T00:25:00"
position = bisect_left(times, late)
insort(times, late)
print("inserted at", position)
for t in times:
print(t)
assert times == sorted(times)
assert times[position] == late
Output
inserted at 3
2024-05-01T00:00:00
2024-05-01T00:10:00
2024-05-01T00:20:00
2024-05-01T00:25:00
2024-05-01T00:30:00
2024-05-01T00:40:00

How it works:

  1. bisect_left finds the insertion point, 3, in O(log⁡n)O(\log n) before anything changes.
  2. insort finds the same point and inserts the timestamp there. The insert shifts the two later elements one place right, which is O(n)O(n).
  3. ISO timestamps compare as text in time order, so no conversion to datetime is needed.

Alternative: times.append(late) followed by times.sort() gives the same list. Timsort sees a sorted run plus one element and sorts it in about nn comparisons. For one element, insort is clearer.

M17-W04 · Sort products by price, then by name

Section titled “M17-W04 · Sort products by price, then by name”
Warm-up

Sort the six products below by price from high to low. Two products cost the same; order those by name from A to Z. Use one sorted() call with a tuple key.

Expected output
99.99 Fitness Tracker
59.99 Slim Fit Jeans
34.99 Non-Slip Yoga Mat
34.99 Statistics Made Simple
14.99 Running Socks 3-Pack
14.99 The Mindful Runner
Starter
products = [
("Running Socks 3-Pack", 14.99), ("Statistics Made Simple", 34.99),
("Non-Slip Yoga Mat", 34.99), ("Slim Fit Jeans", 59.99),
("The Mindful Runner", 14.99), ("Fitness Tracker", 99.99),
]
# TODO: sort by price descending, then name ascending, and print each line
Hint 1

reverse=True would reverse both parts of the key. Negate only the number.

Hint 2

key=lambda p: (-p[1], p[0]).

Solution
products = [
("Running Socks 3-Pack", 14.99), ("Statistics Made Simple", 34.99),
("Non-Slip Yoga Mat", 34.99), ("Slim Fit Jeans", 59.99),
("The Mindful Runner", 14.99), ("Fitness Tracker", 99.99),
]
ranked = sorted(products, key=lambda p: (-p[1], p[0]))
for name, price in ranked:
print(f"{price:>6.2f} {name}")
assert ranked[0][0] == "Fitness Tracker"
assert [n for n, _ in ranked[2:4]] == ["Non-Slip Yoga Mat", "Statistics Made Simple"]
Output
99.99 Fitness Tracker
59.99 Slim Fit Jeans
34.99 Non-Slip Yoga Mat
34.99 Statistics Made Simple
14.99 Running Socks 3-Pack
14.99 The Mindful Runner

How it works:

  1. The key returns (-price, name). Python compares the first element first, so the most expensive product has the smallest key.
  2. Only when two prices are equal does Python compare the names, in normal A-to-Z order.
  3. The original list is unchanged; sorted() returns a new one.

Alternative: two stable passes: sorted(products, key=itemgetter(0)) first, then sort that result with key=itemgetter(1), reverse=True. The second pass keeps the name order among equal prices.

M17-W05 · Fix the bug: the queue serves the newest ticket first

Section titled “M17-W05 · Fix the bug: the queue serves the newest ticket first”
Warm-up

Fix the bug: a support desk must answer tickets in arrival order. This code answers the newest ticket first.

tickets = ["T101 login fails", "T102 invoice missing", "T103 app crash"]
tickets.append("T104 refund request")
while tickets:
print("answer", tickets.pop())
Output
answer T104 refund request
answer T103 app crash
answer T102 invoice missing
answer T101 login fails

Change the code so the tickets come out first in, first out, with an O(1)O(1) removal at the front.

Expected output
answer T101 login fails
answer T102 invoice missing
answer T103 app crash
answer T104 refund request
Starter
tickets = ["T101 login fails", "T102 invoice missing", "T103 app crash"]
tickets.append("T104 refund request")
while tickets:
print("answer", tickets.pop()) # TODO: serve the oldest ticket first
Hint 1

list.pop() removes from the end: that makes a stack (LIFO). A queue removes from the front.

Hint 2

list.pop(0) works but costs O(n)O(n). Make the list a deque and use popleft().

Solution
tickets = deque(["T101 login fails", "T102 invoice missing", "T103 app crash"])
tickets.append("T104 refund request")
answered = []
while tickets:
ticket = tickets.popleft()
answered.append(ticket)
print("answer", ticket)
assert answered[0].startswith("T101")
assert answered[-1].startswith("T104")
Output
answer T101 login fails
answer T102 invoice missing
answer T103 app crash
answer T104 refund request

How it works:

  1. deque(...) wraps the same tickets in a double-ended queue.
  2. append still adds at the back. popleft removes from the front in O(1)O(1), so the oldest ticket comes out first.
  3. An empty deque is falsy, so while tickets stops when every ticket is answered.

Alternative: tickets.pop(0) on a list gives the same order. Each call shifts all remaining items, so a queue of 100,000 tickets would make billions of moves in total. Use it only for tiny lists.

Warm-up

A data-cleaning tool renames a column step by step. Push each old name onto a history stack before you apply the new name. Apply the renames "Rev", "revenue_usd", "revenue_eur" to the start name "Revenue ", then undo two steps. Print the name after each action.

Expected output
rename -> 'Rev'
rename -> 'revenue_usd'
rename -> 'revenue_eur'
undo -> 'revenue_usd'
undo -> 'Rev'
history: ['Revenue ']
Starter
name = "Revenue "
history: list[str] = []
# TODO: for each new name: push the current name, then rename and print
# TODO: undo twice: pop the previous name and print
Hint 1

Push with history.append(name) before name = new_name.

Hint 2

Undo is name = history.pop(). Use repr(name) in the print to show the trailing space of the start name.

Solution
name = "Revenue "
history: list[str] = []
for new_name in ["Rev", "revenue_usd", "revenue_eur"]:
history.append(name)
name = new_name
print("rename ->", repr(name))
for _ in range(2):
name = history.pop()
print("undo ->", repr(name))
print("history:", history)
assert name == "Rev"
assert history == ["Revenue "]
Output
rename -> 'Rev'
rename -> 'revenue_usd'
rename -> 'revenue_eur'
undo -> 'revenue_usd'
undo -> 'Rev'
history: ['Revenue ']

How it works:

  1. Before each rename, the current name goes on top of the stack.
  2. Each undo pops the top of the stack: the name before the most recent rename. LIFO order walks back one step at a time.
  3. After two undos, one entry is left: the original name, ready for a third undo.

Alternative: keep a list of all names, versions = ["Revenue ", "Rev", ...], and undo with versions.pop(); the current name is versions[-1]. It is the same stack, holding the current state on top.

M17-W07 · The three cheapest products with nsmallest

Section titled “M17-W07 · The three cheapest products with nsmallest”
Warm-up

Read data/products.csv and print the three cheapest products by unit_price, cheapest first. Use heapq.nsmallest with a key. Two products cost 14.99; nsmallest keeps the file order for ties.

Expected output
P014 14.99 Running Socks 3-Pack
P025 14.99 The Mindful Runner
P030 15.99 Mineral Sunscreen SPF 50
Starter
with open("data/products.csv", newline="") as f:
products = list(csv.DictReader(f))
# TODO: three cheapest by float(unit_price), printed as "P014 14.99 Running Socks 3-Pack"
Hint 1

The prices are text in the CSV. The key must convert: key=lambda p: float(p["unit_price"]).

Hint 2

heapq.nsmallest(3, products, key=...) returns a list of the three row dicts, smallest first.

Solution
with open("data/products.csv", newline="") as f:
products = list(csv.DictReader(f))
cheapest = heapq.nsmallest(3, products, key=lambda p: float(p["unit_price"]))
for p in cheapest:
print(p["product_id"], p["unit_price"], p["product"])
by_sort = sorted(products, key=lambda p: float(p["unit_price"]))[:3]
assert cheapest == by_sort
assert [p["product_id"] for p in cheapest[:2]] == ["P014", "P025"]
Output
P014 14.99 Running Socks 3-Pack
P025 14.99 The Mindful Runner
P030 15.99 Mineral Sunscreen SPF 50

How it works:

  1. The key converts each price to a float, so "119.00" and "14.99" compare as numbers.
  2. nsmallest keeps a heap of three candidates while it reads the 30 rows: O(nlog⁡k)O(n \log k).
  3. P014 and P025 both cost 14.99. Like sorted(), nsmallest keeps them in input order, so the assert against the sorted version passes.

Alternative: min(products, key=...) gives only the cheapest one; nsmallest(1, ...) gives it inside a list. For a full ranking, use sorted().

M17-W08 · Count the statuses of a sensor in one pass

Section titled “M17-W08 · Count the statuses of a sensor in one pass”
Warm-up

Count the status values (ok, warn, fail) of sensor S4 in data/sensors.csv with a plain dict and dict.get, in one pass over the file. Then check your counts with Counter.

Expected output
ok 1597
warn 400
fail 19
Starter
counts: dict[str, int] = {}
with open("data/sensors.csv", newline="") as f:
for row in csv.DictReader(f):
pass # TODO: count the status of the S4 rows
# TODO: print the counts, most frequent first
Hint 1

counts[key] = counts.get(key, 0) + 1 adds 1 and starts missing keys at 0.

Hint 2

To print the most frequent first: sorted(counts.items(), key=itemgetter(1), reverse=True).

Solution
counts: dict[str, int] = {}
s4_statuses: list[str] = []
with open("data/sensors.csv", newline="") as f:
for row in csv.DictReader(f):
if row["sensor_id"] == "S4":
status = row["status"]
counts[status] = counts.get(status, 0) + 1
s4_statuses.append(status)
for status, n in sorted(counts.items(), key=itemgetter(1), reverse=True):
print(f"{status:<5} {n:>5}")
assert counts == Counter(s4_statuses)
assert sum(counts.values()) == 2016
Output
ok 1597
warn 400
fail 19

How it works:

  1. Each S4 row costs one dict lookup and one store, both O(1)O(1) on average. The whole count is one O(n)O(n) pass.
  2. counts.get(status, 0) returns 0 the first time a status appears, so no if is needed.
  3. The asserts compare with Counter and check that all 2,016 readings of S4 were counted.

Alternative: Counter(row["status"] for row in rows if row["sensor_id"] == "S4").most_common() does the count and the ranking in one line.

M17-C01 · Binary search by hand on sensor timestamps

Section titled “M17-C01 · Binary search by hand on sensor timestamps”
Core

Load the timestamps of sensor S2 from data/sensors.csv. Write first_at_or_after(times, target) that returns the index of the first timestamp at or after target and the number of comparisons. Use the half-open loop while lo < hi. Answer the questions for 2024-05-10T07:33:00 and for a time before the first reading, and check both against bisect_left.

Expected output
2024-05-10T07:33:00 -> 1342 2024-05-10T07:40:00 (11 comparisons)
2024-04-30T23:00:00 -> 0 2024-05-01T00:00:00 (11 comparisons)
Starter
with open("data/sensors.csv", newline="") as f:
times = [r["timestamp"] for r in csv.DictReader(f) if r["sensor_id"] == "S2"]
def first_at_or_after(times: list[str], target: str) -> tuple[int, int]:
lo, hi = 0, len(times)
comparisons = 0
# TODO: halve [lo, hi) until lo == hi, counting each comparison
return lo, comparisons
# TODO: answer for "2024-05-10T07:33:00" and "2024-04-30T23:00:00"
Hint 1

mid = (lo + hi) // 2. If times[mid] < target, the answer is right of mid: lo = mid + 1. Otherwise mid may be the answer: hi = mid.

Hint 2

A target before every reading returns 0. A target after every reading returns len(times); check i < len(times) before you read times[i].

Solution
with open("data/sensors.csv", newline="") as f:
times = [r["timestamp"] for r in csv.DictReader(f) if r["sensor_id"] == "S2"]
def first_at_or_after(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
for target in ["2024-05-10T07:33:00", "2024-04-30T23:00:00"]:
i, steps = first_at_or_after(times, target)
print(target, "->", i, times[i], f"({steps} comparisons)")
assert i == bisect_left(times, target)
assert steps <= math.ceil(math.log2(len(times) + 1))
Output
2024-05-10T07:33:00 -> 1342 2024-05-10T07:40:00 (11 comparisons)
2024-04-30T23:00:00 -> 0 2024-05-01T00:00:00 (11 comparisons)

How it works:

  1. The interval [lo, hi) always contains the answer. Each comparison halves it, so 2,016 timestamps need at most 11 comparisons.
  2. 07:33 lies between two readings, so the answer is the 07:40 reading.
  3. A target before the first reading returns index 0, the first reading.
  4. The last assert checks the bound ⌈log⁡2(n+1)⌉\lceil \log_2(n + 1) \rceil from the lesson.

Alternative: bisect_left(times, target) gives the same index in one call. Write the loop by hand when you must count the steps or search on a computed condition.

M17-C02 · Price bands for the product catalog

Section titled “M17-C02 · Price bands for the product catalog”
Core

The shop groups its 30 products into price bands: below 25 is budget, 25 up to below 100 is mid, 100 up to below 500 is premium, and 500 or more is luxury. Assign each product of data/products.csv to a band with bisect_right and one list of cut points, then print the number of products per band and the products in luxury.

Expected output
budget 8
mid 10
premium 10
luxury 2
luxury: ['55-inch 4K Smart TV', '14-inch Ultrabook Laptop']
Starter
cuts = [25.0, 100.0, 500.0]
labels = ["budget", "mid", "premium", "luxury"]
with open("data/products.csv", newline="") as f:
products = list(csv.DictReader(f))
# TODO: band of each product with bisect_right, then counts and the luxury list
Hint 1

bisect_right(cuts, price) is the number of cut points less than or equal to price. That number is the index into labels.

Hint 2

A price of exactly 25.0 must be mid. bisect_right(cuts, 25.0) is 1, so it is.

Solution
cuts = [25.0, 100.0, 500.0]
labels = ["budget", "mid", "premium", "luxury"]
with open("data/products.csv", newline="") as f:
products = list(csv.DictReader(f))
bands: dict[str, list[str]] = defaultdict(list)
for p in products:
band = labels[bisect_right(cuts, float(p["unit_price"]))]
bands[band].append(p["product"])
for label in labels:
print(f"{label:<8} {len(bands[label]):>2}")
print("luxury:", bands["luxury"])
assert labels[bisect_right(cuts, 25.0)] == "mid"
assert labels[bisect_right(cuts, 24.99)] == "budget"
assert sum(len(v) for v in bands.values()) == 30
Output
budget 8
mid 10
premium 10
luxury 2
luxury: ['55-inch 4K Smart TV', '14-inch Ultrabook Laptop']

How it works:

  1. Three cut points make four bands. bisect_right returns 0, 1, 2 or 3, which indexes labels directly.
  2. bisect_right puts a price that equals a cut into the upper band, as the rule asks. The first two asserts test both sides of the 25.0 edge.
  3. defaultdict(list) groups the product names per band in the same pass.

Alternative: an if/elif chain gives the same bands. It grows by two lines per band and is easy to get wrong at the edges; the cut list grows by one number.

M17-C03 · Fix the bug: a binary search that misses the end

Section titled “M17-C03 · Fix the bug: a binary search that misses the end”
Core

Fix the bug: this search should return the first reading of sensor S1 at or after a time. For a time after the last reading, it must return len(times), so the caller knows there is no such reading. Instead, it returns the last reading, which is before the requested time.

with open("data/sensors.csv", newline="") as f:
times = [r["timestamp"] for r in csv.DictReader(f) if r["sensor_id"] == "S1"]
def first_at_or_after(times: list[str], target: str) -> int:
lo, hi = 0, len(times) - 1
while lo < hi:
mid = (lo + hi) // 2
if times[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
i = first_at_or_after(times, "2024-05-15T00:00:00")
print(i, times[i])
Output
2015 2024-05-14T23:50:00

Fix the function so that all three checks below print True.

Expected output
2024-05-15T00:00:00 True
2024-05-14T23:50:00 True
2024-05-01T00:00:00 True
Starter
def first_at_or_after(times: list[str], target: str) -> int:
lo, hi = 0, len(times) - 1 # TODO: fix the interval
while lo < hi:
mid = (lo + hi) // 2
if times[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
# TODO: print the three checks against bisect_left
Hint 1

The loop treats [lo, hi) as a half-open interval: hi itself is never a candidate. Which index can the function never return?

Hint 2

len(times) must be a possible answer, so the interval must start as [0, len(times)).

Solution
with open("data/sensors.csv", newline="") as f:
times = [r["timestamp"] for r in csv.DictReader(f) if r["sensor_id"] == "S1"]
def first_at_or_after(times: list[str], target: str) -> int:
lo, hi = 0, len(times) # len(times) is a valid answer: "no such reading"
while lo < hi:
mid = (lo + hi) // 2
if times[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
checks = ["2024-05-15T00:00:00", "2024-05-14T23:50:00", "2024-05-01T00:00:00"]
for target in checks:
print(target, first_at_or_after(times, target) == bisect_left(times, target))
assert first_at_or_after(times, "2024-05-15T00:00:00") == len(times)
assert first_at_or_after(times, "2024-05-14T23:50:00") == len(times) - 1
Output
2024-05-15T00:00:00 True
2024-05-14T23:50:00 True
2024-05-01T00:00:00 True

How it works:

  1. With hi = len(times) - 1, the loop can never return len(times). A target after the last reading ends at lo == hi == 2015, the last index, which is wrong.
  2. With hi = len(times), the half-open interval [lo, hi) covers every possible insertion point, from 0 to len(times).
  3. The checks cover the three edge cases: after the end, exactly the last element and exactly the first element. Edge cases are where binary searches break.

Alternative: a closed-interval version (hi = len(times) - 1, while lo <= hi, hi = mid - 1) also works, but it needs a separate variable for the answer. Pick one style and keep it; mixing the two causes this bug.

M17-C04 · Count sales in a date range with two bisects

Section titled “M17-C04 · Count sales in a date range with two bisects”
Core

data/sales.csv is sorted by order_date. Count the sales lines of December 2023 and their total revenue. Find the first and the last position with bisect_left and bisect_right on the list of dates, and slice. Check the count with a full scan.

Expected output
lines 7808..9080: 1273 lines, revenue 241,098.45
first: 2023-12-01 | last: 2023-12-31
Starter
with open("data/sales.csv", newline="") as f:
sales = list(csv.DictReader(f))
dates = [row["order_date"] for row in sales]
# TODO: start = first index on or after 2023-12-01, end = first index after 2023-12-31
# TODO: print the count and the revenue of sales[start:end]
Hint 1

start = bisect_left(dates, "2023-12-01"). For the end, use bisect_right(dates, "2023-12-31"), so the last day is included.

Hint 2

The revenue is text. Sum float(row["revenue"]) over the slice and round the total to 2 decimals.

Solution
with open("data/sales.csv", newline="") as f:
sales = list(csv.DictReader(f))
dates = [row["order_date"] for row in sales]
assert dates == sorted(dates)
start = bisect_left(dates, "2023-12-01")
end = bisect_right(dates, "2023-12-31")
december = sales[start:end]
revenue = round(sum(float(row["revenue"]) for row in december), 2)
print(f"lines {start}..{end - 1}: {len(december)} lines, revenue {revenue:,.2f}")
print("first:", december[0]["order_date"], "| last:", december[-1]["order_date"])
scan = sum(1 for d in dates if "2023-12-01" <= d <= "2023-12-31")
assert scan == len(december)
Output
lines 7808..9080: 1273 lines, revenue 241,098.45
first: 2023-12-01 | last: 2023-12-31

How it works:

  1. The first assert confirms the precondition: the dates are sorted.
  2. bisect_left finds the first December line. bisect_right with the last day finds the position just after the last December line, so the slice [start:end] holds exactly the month.
  3. Two binary searches cost about 30 comparisons. The scan compares all 20,228 dates. The total matches the 241,098 of the data dictionary.

Alternative: bisect_left(dates, "2024-01-01") for the end works too: the first position on or after the next month. It avoids month lengths.

Core

Sort the 12 stores of data/stores.csv by region from A to Z and, inside each region, by city from Z to A. A tuple key cannot reverse a text field, so use two stable passes with itemgetter. Print region and city.

Expected output
East Philadelphia
East New York
East Boston
North Minneapolis
North Detroit
North Chicago
South Miami
South Houston
South Atlanta
West Seattle
West San Francisco
West Denver
Starter
with open("data/stores.csv", newline="") as f:
stores = list(csv.DictReader(f))
# TODO: pass 1: city descending; pass 2: region ascending
Hint 1

Run the passes from the least important key to the most important one.

Hint 2

sorted(stores, key=itemgetter("city"), reverse=True), then sort that result with key=itemgetter("region").

Solution
with open("data/stores.csv", newline="") as f:
stores = list(csv.DictReader(f))
by_city = sorted(stores, key=itemgetter("city"), reverse=True)
ordered = sorted(by_city, key=itemgetter("region"))
for s in ordered:
print(f"{s['region']:<6} {s['city']}")
regions = [s["region"] for s in ordered]
assert regions == sorted(regions)
for region in set(regions):
cities = [s["city"] for s in ordered if s["region"] == region]
assert cities == sorted(cities, reverse=True)
Output
East Philadelphia
East New York
East Boston
North Minneapolis
North Detroit
North Chicago
South Miami
South Houston
South Atlanta
West Seattle
West San Francisco
West Denver

How it works:

  1. Pass 1 orders all 12 stores by city, Z to A.
  2. Pass 2 orders by region. Timsort is stable, so the three stores of each region keep the city order of pass 1.
  3. The asserts check both rules: regions ascend, and the cities inside each region descend.

Alternative: for a text key, you can build a key that reverses the order by hand, such as a tuple of negated character codes: key=lambda s: (s["region"], [-ord(c) for c in s["city"]]). It works for these names but is hard to read and fails on prefixes. Stable passes are clearer.

M17-C06 · Interpret a result: Timsort on daily revenue

Section titled “M17-C06 · Interpret a result: Timsort on daily revenue”
Core

Interpret a result: count how many comparisons sorted() makes on the 731 daily revenue totals of data/sales.csv in three orders: in date order, already sorted by revenue, and sorted from high to low. Print the counts next to n−1n - 1 and nlog⁡2nn \log_2 n. Then explain each count in one sentence.

Expected output
date order 5973
ascending 730
descending 730
n - 1 = 730, n log2 n = 6955
Starter
def count_comparisons(values: list[float]) -> int:
calls = 0
def compare(a: float, b: float) -> int:
nonlocal calls
calls += 1
return (a > b) - (a < b)
sorted(values, key=cmp_to_key(compare))
return calls
# TODO: daily totals in date order, then the three counts
Hint 1

Build the totals with defaultdict(float), keyed by order_date. [daily[d] for d in sorted(daily)] gives them in date order.

Hint 2

Timsort looks for runs: stretches that are already ascending or strictly descending. How many runs does each input have?

Solution
def count_comparisons(values: list[float]) -> int:
calls = 0
def compare(a: float, b: float) -> int:
nonlocal calls
calls += 1
return (a > b) - (a < b)
sorted(values, key=cmp_to_key(compare))
return calls
daily: dict[str, float] = defaultdict(float)
with open("data/sales.csv", newline="") as f:
for row in csv.DictReader(f):
daily[row["order_date"]] += float(row["revenue"])
by_date = [daily[d] for d in sorted(daily)]
n = len(by_date)
counts = {
"date order": count_comparisons(by_date),
"ascending": count_comparisons(sorted(by_date)),
"descending": count_comparisons(sorted(by_date, reverse=True)),
}
for label, c in counts.items():
print(f"{label:<11} {c:>5}")
print(f"n - 1 = {n - 1}, n log2 n = {n * math.log2(n):.0f}")
assert counts["ascending"] == counts["descending"] == n - 1
assert counts["date order"] < n * math.log2(n)
Output
date order 5973
ascending 730
descending 730
n - 1 = 730, n log2 n = 6955

How it works:

  1. Ascending: the input is one run. Timsort checks each neighbor pair once, n−1=730n - 1 = 730 comparisons, and stops.
  2. Descending: the input is one strictly descending run. Timsort reverses it in place, again with 730 comparisons. (A descending run must be strictly descending; equal neighbors end it, so the sort stays stable.)
  3. Date order: daily revenue goes up and down with the weekdays, so the runs are short. Timsort merges them and needs a number of comparisons close to, but below, nlog⁡2n≈6,955n \log_2 n \approx 6{,}955.
  4. Interpretation: Timsort is cheap on data that is already in order and never worse than O(nlog⁡n)O(n \log n). So appending a few rows to sorted data and calling sort() again is fine.

Alternative: the timeit module (module 15) would show the same pattern in seconds, but the numbers would change from run to run. Comparison counts are exact.

M17-C07 · Bracket checker that skips quoted text

Section titled “M17-C07 · Bracket checker that skips quoted text”
Core

A JSON config can contain brackets inside string values, such as "pattern": "[A-Z]{3}". The lesson’s stack checker would treat those as real brackets. Write check_brackets(text) that ignores every character between double quotes (a \" escape inside a string does not end it). Return "balanced" or the first problem with its 1-based character position.

Expected output
{"pattern": "[A-Z]{3}", "ids": [1, 2]} balanced
{"note": "say \"hi]\"", "x": [1} unexpected '}' at 32
{"a": [1, 2] '{' at 1 is never closed
Starter
PAIRS = {")": "(", "]": "[", "}": "{"}
def check_brackets(text: str) -> str:
stack: list[tuple[str, int]] = []
in_string = False
escaped = False
for pos, char in enumerate(text, start=1):
pass # TODO: track strings, then push openers and match closers
return "balanced"
tests = [
'{"pattern": "[A-Z]{3}", "ids": [1, 2]}',
'{"note": "say \\"hi]\\"", "x": [1}',
'{"a": [1, 2]',
]
# TODO: print each test and its result
Hint 1

Handle strings first. Inside a string: a backslash sets escaped, a quote that is not escaped ends the string, and every other character is skipped.

Hint 2

Outside a string, a " starts one. The bracket logic is the lesson’s: push openers with their position; a closer must match stack[-1].

Solution
PAIRS = {")": "(", "]": "[", "}": "{"}
def check_brackets(text: str) -> str:
stack: list[tuple[str, int]] = []
in_string = False
escaped = False
for pos, char in enumerate(text, start=1):
if in_string:
if escaped:
escaped = False
elif char == "\\":
escaped = True
elif char == '"':
in_string = False
continue
if char == '"':
in_string = True
elif char in "([{":
stack.append((char, pos))
elif char in PAIRS:
if not stack or stack[-1][0] != PAIRS[char]:
return f"unexpected {char!r} at {pos}"
stack.pop()
if stack:
return f"{stack[-1][0]!r} at {stack[-1][1]} is never closed"
return "balanced"
tests = [
'{"pattern": "[A-Z]{3}", "ids": [1, 2]}',
'{"note": "say \\"hi]\\"", "x": [1}',
'{"a": [1, 2]',
]
for text in tests:
print(f"{text:<42} {check_brackets(text)}")
assert check_brackets(tests[0]) == "balanced"
assert json.loads(tests[0])["pattern"] == "[A-Z]{3}"
Output
{"pattern": "[A-Z]{3}", "ids": [1, 2]} balanced
{"note": "say \"hi]\"", "x": [1} unexpected '}' at 32
{"a": [1, 2] '{' at 1 is never closed

How it works:

  1. Three states drive the loop: outside a string, inside a string, and just after a backslash inside a string.
  2. Inside a string, every character is skipped, so [A-Z]{3} and hi] do not touch the stack.
  3. Outside strings, the stack logic is unchanged. In test 2, the list [ is still open when } arrives at position 32.
  4. In test 3, the outer { is never closed. json.loads agrees that test 1 is valid JSON.

Alternative: for real JSON, call json.loads(text) and catch json.JSONDecodeError; its lineno and colno attributes locate the problem. A hand-written checker is useful for formats that have no parser, such as a template language.

M17-C08 · BFS: fewest hops in a delivery network

Section titled “M17-C08 · BFS: fewest hops in a delivery network”
Core

A delivery network connects a warehouse W to stores by direct van routes. Each route works in both directions. Find the fewest hops from W to every store with BFS, and rebuild the shortest route to S12 (Denver) from a parent dict.

Expected output
S01 1
S02 2
S03 2
S04 1
S05 2
S06 3
S07 1
S08 2
S09 3
S10 3
S11 4
S12 3
W 0
route to S12: W -> S04 -> S05 -> S12
Starter
routes = [("W", "S01"), ("W", "S04"), ("W", "S07"), ("S01", "S02"), ("S01", "S03"),
("S04", "S05"), ("S05", "S06"), ("S07", "S08"), ("S08", "S09"),
("S02", "S10"), ("S10", "S11"), ("S10", "S12"), ("S05", "S12")]
graph: dict[str, list[str]] = defaultdict(list)
# TODO: add both directions of each route
# TODO: BFS from "W" with a deque, a hops dict and a parent dict
Hint 1

graph[a].append(b) and graph[b].append(a) for each route. The graph has a cycle, so keep a record of visited nodes: a node is visited once it is in hops.

Hint 2

When BFS first reaches a neighbor, set hops[nb] = hops[node] + 1 and parent[nb] = node. To rebuild the route, follow parent from S12 back to W, then reverse the list.

Solution
routes = [("W", "S01"), ("W", "S04"), ("W", "S07"), ("S01", "S02"), ("S01", "S03"),
("S04", "S05"), ("S05", "S06"), ("S07", "S08"), ("S08", "S09"),
("S02", "S10"), ("S10", "S11"), ("S10", "S12"), ("S05", "S12")]
graph: dict[str, list[str]] = defaultdict(list)
for a, b in routes:
graph[a].append(b)
graph[b].append(a)
hops = {"W": 0}
parent: dict[str, str] = {}
queue = deque(["W"])
while queue:
node = queue.popleft()
for nb in graph[node]:
if nb not in hops: # first visit = shortest distance in BFS
hops[nb] = hops[node] + 1
parent[nb] = node
queue.append(nb)
for store in sorted(hops):
print(f"{store:<4} {hops[store]}")
route = ["S12"]
while route[-1] != "W":
route.append(parent[route[-1]])
print("route to S12:", " -> ".join(reversed(route)))
assert hops["S12"] == 3
assert len(hops) == 13
Output
S01 1
S02 2
S03 2
S04 1
S05 2
S06 3
S07 1
S08 2
S09 3
S10 3
S11 4
S12 3
W 0
route to S12: W -> S04 -> S05 -> S12

How it works:

  1. The adjacency list stores each route twice, once per direction.
  2. BFS takes nodes in order of distance: all 1-hop stores, then all 2-hop stores, and so on. So the first time it reaches a store, it has found the fewest hops.
  3. if nb not in hops is the visited check. Without it, the cycle W–S01–S02–S10–S12–S05–S04–W would keep the walk going forever.
  4. S12 can be reached by W → S01 → S02 → S10 → S12 (4 hops) or W → S04 → S05 → S12 (3 hops). BFS finds the 3-hop route.

Alternative: DFS with a stack also visits every store, but the first path it finds is not always the shortest. For fewest hops on an unweighted graph, use BFS. For routes with distances in km, the standard algorithm is Dijkstra’s, which replaces the queue with a heap.

Core

Total the revenue per customer in data/sales.csv with a dict, then print the 5 customers with the highest totals using heapq.nlargest. Round each total to cents. Customers with equal totals must come out by customer id, lowest first. Test the tie rule on a tiny hand-made dict, and check the result against a full sort.

Expected output
1. C01364 16,023.65
2. C01766 13,341.26
3. C01656 12,785.14
4. C01860 11,353.72
5. C00587 10,590.79
3254 customers with orders
tie test: [('C00001', 80.0), ('C00002', 80.0), ('C00005', 80.0)]
Starter
totals: dict[str, float] = defaultdict(float)
with open("data/sales.csv", newline="") as f:
for row in csv.DictReader(f):
pass # TODO: add the revenue to the customer's total
# TODO: top 5 with heapq.nlargest
Hint 1

totals[row["customer_id"]] += float(row["revenue"]).

Hint 2

heapq.nlargest(5, totals.items(), key=itemgetter(1)) returns (customer_id, total) pairs, largest first.

Hint 3

nlargest puts the largest key first, so a plain id in the key would put C00002 before C00001. Negate the number in the id: key=lambda kv: (kv[1], -int(kv[0][1:])).

Solution
totals: dict[str, float] = defaultdict(float)
with open("data/sales.csv", newline="") as f:
for row in csv.DictReader(f):
totals[row["customer_id"]] += float(row["revenue"])
def top_customers(totals: dict[str, float], k: int) -> list[tuple[str, float]]:
"""k highest totals; equal totals by customer id, lowest first."""
rounded = ((c, round(v, 2)) for c, v in totals.items())
return heapq.nlargest(k, rounded, key=lambda kv: (kv[1], -int(kv[0][1:])))
top_5 = top_customers(totals, 5)
for rank, (customer, total) in enumerate(top_5, start=1):
print(f"{rank}. {customer} {total:>10,.2f}")
print(len(totals), "customers with orders")
tie = {"C00009": 50.0, "C00002": 80.0, "C00001": 80.0, "C00005": 80.0}
print("tie test:", top_customers(tie, 3))
by_id = sorted(((c, round(v, 2)) for c, v in totals.items()), key=itemgetter(0))
full = sorted(by_id, key=itemgetter(1), reverse=True)[:5] # stable two-pass check
assert top_5 == full
assert [c for c, _ in top_customers(tie, 3)] == ["C00001", "C00002", "C00005"]
Output
1. C01364 16,023.65
2. C01766 13,341.26
3. C01656 12,785.14
4. C01860 11,353.72
5. C00587 10,590.79
3254 customers with orders
tie test: [('C00001', 80.0), ('C00002', 80.0), ('C00005', 80.0)]

How it works:

  1. One pass over 20,228 lines builds 3,254 totals in a dict.
  2. nlargest reads the 3,254 pairs and keeps 5 candidates in a heap, O(nlog⁡5)O(n \log 5).
  3. nlargest takes the largest keys. The key (total, -id_number) makes a lower id the larger key among equal totals, so ties come out by id, lowest first. Text ids cannot be negated, so the key uses the number inside the id.
  4. The real top 5 has no ties, so the tie test checks the rule on hand-made data: three customers at 80.0 come out as C00001, C00002, C00005.
  5. The full-sort check uses two stable passes: by id first, then by total with reverse=True. reverse=True keeps equal totals in their earlier order, which is ascending id.

Alternative: Counter adds up numbers too: c = Counter(); c[customer] += revenue, then c.most_common(5). most_common(k) uses heapq.nlargest internally.

M17-C10 · Merge sorted streams from four sensors

Section titled “M17-C10 · Merge sorted streams from four sensors”
Core

A gateway receives one stream per sensor, each sorted by time. Split data/sensors.csv into four lists of (timestamp, sensor_id, temperature_c), one per sensor. Merge them with heapq.merge and check that the merged stream equals the file order (which is sorted by timestamp, then by sensor id). Print the first 6 merged items.

Expected output
('2024-05-01T00:00:00', 'S1', '20.21')
('2024-05-01T00:00:00', 'S2', '22.3')
('2024-05-01T00:00:00', 'S3', '19.4')
('2024-05-01T00:00:00', 'S4', '24.52')
('2024-05-01T00:10:00', 'S1', '20.22')
('2024-05-01T00:10:00', 'S2', '22.44')
4 streams, 8064 items, same order: True
Starter
streams: dict[str, list[tuple[str, str, str]]] = defaultdict(list)
with open("data/sensors.csv", newline="") as f:
file_order = []
for row in csv.DictReader(f):
item = (row["timestamp"], row["sensor_id"], row["temperature_c"])
file_order.append(item)
# TODO: add item to the stream of its sensor
# TODO: merge the four streams with heapq.merge
Hint 1

heapq.merge(*streams.values()) merges any number of sorted iterables. It returns an iterator.

Hint 2

Tuples compare element by element: by timestamp first, then by sensor id when two readings share a timestamp. That matches the file order.

Solution
streams: dict[str, list[tuple[str, str, str]]] = defaultdict(list)
with open("data/sensors.csv", newline="") as f:
file_order = []
for row in csv.DictReader(f):
item = (row["timestamp"], row["sensor_id"], row["temperature_c"])
file_order.append(item)
streams[row["sensor_id"]].append(item)
merged = list(heapq.merge(*streams.values()))
for item in merged[:6]:
print(item)
print(len(streams), "streams,", len(merged), "items, same order:", merged == file_order)
assert all(s == sorted(s) for s in streams.values())
assert merged == file_order
Output
('2024-05-01T00:00:00', 'S1', '20.21')
('2024-05-01T00:00:00', 'S2', '22.3')
('2024-05-01T00:00:00', 'S3', '19.4')
('2024-05-01T00:00:00', 'S4', '24.52')
('2024-05-01T00:10:00', 'S1', '20.22')
('2024-05-01T00:10:00', 'S2', '22.44')
4 streams, 8064 items, same order: True

How it works:

  1. Each stream is sorted by time, which the first assert confirms. That is the precondition of merge.
  2. heapq.merge keeps one item per stream in a heap of size 4 and yields the smallest. Each of the 8,064 items costs O(log⁡4)O(\log 4).
  3. At 00:00, all four sensors have a reading. The tuples tie on the timestamp, so the sensor id decides: S1, S2, S3, S4, as in the file.
  4. temperature_c stays text here: a blank cell would break float(), and the merge does not need numbers.

Alternative: sorted(item for s in streams.values() for item in s) gives the same list. It needs all data in memory and costs O(nlog⁡n)O(n \log n); merge is lazy and suits streams from files or sockets that you read item by item.

M17-C11 · Two-sum: find bundle pairs in the catalog

Section titled “M17-C11 · Two-sum: find bundle pairs in the catalog”
Core

The shop wants to sell two different products as a bundle for exactly 94.98. Find every pair of products in data/products.csv whose list prices add up to 94.98. Use a hash map of prices in cents and one pass. Print each pair with the cheaper product first, sorted, and the number of dict lookups.

Expected output
34.99 + 59.99 Non-Slip Yoga Mat + Electric Toothbrush
34.99 + 59.99 Non-Slip Yoga Mat + Slim Fit Jeans
14.99 + 79.99 Running Socks 3-Pack + Wireless Earbuds
34.99 + 59.99 Statistics Made Simple + Electric Toothbrush
34.99 + 59.99 Statistics Made Simple + Slim Fit Jeans
14.99 + 79.99 The Mindful Runner + Wireless Earbuds
24.99 + 69.99 Vitamin C Face Serum + Cotton Bed Sheet Set
7 pairs, 30 lookups
Starter
with open("data/products.csv", newline="") as f:
products = list(csv.DictReader(f))
target = 9498 # 94.98 in cents
seen: dict[int, list[str]] = defaultdict(list) # price in cents -> product names
pairs: list[tuple[str, str]] = []
# TODO: for each product, look up the complement, record pairs, then store the product
Hint 1

cents = round(float(p["unit_price"]) * 100). The complement is target - cents.

Hint 2

Several products can share a price, so seen maps a price to a list of names. Look up before you store, so a product never pairs with itself.

Solution
with open("data/products.csv", newline="") as f:
products = list(csv.DictReader(f))
target = 9498 # 94.98 in cents
seen: dict[int, list[str]] = defaultdict(list) # price in cents -> product names
pairs: list[tuple[str, str]] = []
lookups = 0
price_of: dict[str, int] = {}
for p in products:
cents = round(float(p["unit_price"]) * 100)
price_of[p["product"]] = cents
lookups += 1
for other in seen.get(target - cents, []):
pairs.append(tuple(sorted((other, p["product"]), key=price_of.get)))
seen[cents].append(p["product"])
for a, b in sorted(pairs):
print(f"{price_of[a] / 100:>6.2f} + {price_of[b] / 100:>6.2f} {a} + {b}")
print(len(pairs), "pairs,", lookups, "lookups")
assert all(price_of[a] + price_of[b] == target for a, b in pairs)
brute = sum(1 for i, p in enumerate(products) for q in products[i + 1 :]
if round(float(p["unit_price"]) * 100) + round(float(q["unit_price"]) * 100)
== target)
assert brute == len(pairs)
Output
34.99 + 59.99 Non-Slip Yoga Mat + Electric Toothbrush
34.99 + 59.99 Non-Slip Yoga Mat + Slim Fit Jeans
14.99 + 79.99 Running Socks 3-Pack + Wireless Earbuds
34.99 + 59.99 Statistics Made Simple + Electric Toothbrush
34.99 + 59.99 Statistics Made Simple + Slim Fit Jeans
14.99 + 79.99 The Mindful Runner + Wireless Earbuds
24.99 + 69.99 Vitamin C Face Serum + Cotton Bed Sheet Set
7 pairs, 30 lookups

How it works:

  1. Prices become integer cents, so the sum is exact and the dict lookup cannot miss by a rounding error.
  2. For each product, the dict answers “which earlier products cost exactly target - price?” in O(1)O(1). 30 products need 30 lookups.
  3. The lookup happens before the store, so a product that costs exactly half the target could never pair with itself.
  4. The brute-force check tests all 435 pairs and finds the same 7.

Alternative: sort the prices and walk two pointers from both ends (lesson, Example 7). It also takes one pass after the sort, but repeated prices need extra care to list every pair.

M17-C12 · Refactor: find duplicate lines in linear time

Section titled “M17-C12 · Refactor: find duplicate lines in linear time”
Core

Refactor: data/sales_raw.csv contains exact duplicate rows. The code below finds them by comparing every row with every earlier row. Rewrite it with a set so that it does one pass, and count the operations of both versions. Both must report the same 36 duplicates.

with open("data/sales_raw.csv", newline="") as f:
raw = [tuple(row) for row in csv.reader(f)][1:]
comparisons = 0
duplicates = []
for i, row in enumerate(raw):
for earlier in raw[:i]:
comparisons += 1
if row == earlier:
duplicates.append(i)
break
print(len(duplicates), "duplicates,", f"{comparisons:,} comparisons")
Output
36 duplicates, 718,841 comparisons
Expected output
36 duplicates, 1,200 lookups
first duplicate rows: [29, 88, 155]
Starter
with open("data/sales_raw.csv", newline="") as f:
raw = [tuple(row) for row in csv.reader(f)][1:]
seen: set[tuple[str, ...]] = set()
duplicates_fast = []
lookups = 0
# TODO: one pass: a row already in seen is a duplicate
Hint 1

Rows are tuples of strings, so they are hashable and can go into a set.

Hint 2

if row in seen: ... is one O(1)O(1) lookup. Add the row to seen otherwise.

Solution
with open("data/sales_raw.csv", newline="") as f:
raw = [tuple(row) for row in csv.reader(f)][1:]
seen: set[tuple[str, ...]] = set()
duplicates_fast = []
lookups = 0
for i, row in enumerate(raw):
lookups += 1
if row in seen:
duplicates_fast.append(i)
else:
seen.add(row)
print(len(duplicates_fast), "duplicates,", f"{lookups:,} lookups")
print("first duplicate rows:", duplicates_fast[:3])
assert len(duplicates_fast) == 36
assert len(seen) == len(raw) - 36
Output
36 duplicates, 1,200 lookups
first duplicate rows: [29, 88, 155]

How it works:

  1. The nested loop compares each row with up to all earlier rows: about n2/2n^2 / 2 comparisons, 718,841 for 1,200 rows.
  2. The set version asks one question per row: “have I seen this exact row?”. A set lookup hashes the tuple and is O(1)O(1) on average, so 1,200 rows cost 1,200 lookups.
  3. Both versions flag the later copy of each pair, so the indices match. The duplicates sit up to 30 rows after their originals, as the data dictionary says.
  4. For 1,000,000 rows, the nested loop would need about 500 billion comparisons; the set needs a million lookups.

Alternative: in pandas, df.duplicated() does the same hash-based check (module 26). Without pandas, len(raw) - len(set(raw)) counts the duplicates in one line, but does not tell you where they are.

Core

Compute the daily revenue totals of 2024 from data/sales.csv. Find the 7-day window with the highest total revenue using a running sum: add the day that enters, subtract the day that leaves. Count the additions and subtractions, and check the answer against a version that recomputes sum() for every window.

Expected output
best week: 2024-11-29 to 2024-12-05, 105,692.32
running-sum ops: 725 | recompute ops: 2520
Starter
daily: dict[str, float] = defaultdict(float)
with open("data/sales.csv", newline="") as f:
for row in csv.DictReader(f):
if row["order_date"].startswith("2024"):
daily[row["order_date"]] += float(row["revenue"])
days = sorted(daily)
values = [daily[d] for d in days]
K = 7
# TODO: running sum over windows of K days, track the best window and count the ops
Hint 1

Start with window = sum(values[:K]), which costs K additions. Then, for i from K to the end: window += values[i] - values[i - K].

Hint 2

The window that ends at index i starts at i - K + 1. Store the start index of the best window.

Solution
daily: dict[str, float] = defaultdict(float)
with open("data/sales.csv", newline="") as f:
for row in csv.DictReader(f):
if row["order_date"].startswith("2024"):
daily[row["order_date"]] += float(row["revenue"])
days = sorted(daily)
values = [daily[d] for d in days]
K = 7
window = sum(values[:K])
ops = K
best, best_start = window, 0
for i in range(K, len(values)):
window += values[i] - values[i - K]
ops += 2
if window > best:
best, best_start = window, i - K + 1
print(f"best week: {days[best_start]} to {days[best_start + K - 1]}, {best:,.2f}")
print("running-sum ops:", ops, "| recompute ops:", (len(values) - K + 1) * K)
naive = max(range(len(values) - K + 1), key=lambda s: sum(values[s : s + K]))
assert naive == best_start
assert math.isclose(best, sum(values[best_start : best_start + K]))
Output
best week: 2024-11-29 to 2024-12-05, 105,692.32
running-sum ops: 725 | recompute ops: 2520

How it works:

  1. 2024 has 366 days, so there are 360 windows of 7 days.
  2. The first window costs 7 additions. Each move costs 2 operations, whatever the window size: 7 + 2 × 359 = 725.
  3. The best week contains Black Friday 2024 (2024-11-29) and Cyber Monday (2024-12-02), the promotion peak of the year.
  4. math.isclose compares the running sum with a fresh sum. The running sum collects tiny float errors, so == could fail.

Alternative: itertools.accumulate builds prefix sums: prefix = [0, *accumulate(values)]. The sum of a window from s to s + K - 1 is prefix[s + K] - prefix[s], one subtraction per window. Prefix sums also answer any range-sum question in O(1)O(1).

M17-C14 · Memoize a count of pack combinations

Section titled “M17-C14 · Memoize a count of pack combinations”
Core

Running socks ship in packs of 1, 3 or 5 pairs. In how many different ways can a warehouse fill an order of 40 pairs? Order does not matter: 3 + 1 and 1 + 3 are the same combination. Write a recursive combos(n, i) that uses pack sizes from index i on, count its calls, and compare with a memoized version.

Expected output
66 66
{'plain': 2539, 'memo': 169}
CacheInfo(hits=72, misses=169, maxsize=None, currsize=169)
Starter
SIZES = (1, 3, 5)
calls = {"plain": 0, "memo": 0}
def combos(n: int, i: int = 0) -> int:
calls["plain"] += 1
# TODO: base cases: n == 0 -> 1; n < 0 or i == len(SIZES) -> 0
# TODO: either use one more pack of SIZES[i], or move on to the next size
return 0
# TODO: a @cache version, then compare the results and the calls for n = 40
Hint 1

Two choices at each call: take one pack of SIZES[i] and stay at i (combos(n - SIZES[i], i)), or never use this size again (combos(n, i + 1)). Add both counts.

Hint 2

Staying at index i or moving right, never left, is what makes 3 + 1 and 1 + 3 count once.

Solution
SIZES = (1, 3, 5)
calls = {"plain": 0, "memo": 0}
def combos(n: int, i: int = 0) -> int:
calls["plain"] += 1
if n == 0:
return 1
if n < 0 or i == len(SIZES):
return 0
return combos(n - SIZES[i], i) + combos(n, i + 1)
@cache
def combos_memo(n: int, i: int = 0) -> int:
calls["memo"] += 1
if n == 0:
return 1
if n < 0 or i == len(SIZES):
return 0
return combos_memo(n - SIZES[i], i) + combos_memo(n, i + 1)
print(combos(40), combos_memo(40))
print(calls)
print(combos_memo.cache_info())
assert combos(10) == 7 # 10 ones; 3+7x1; 3+3+4x1; 3+3+3+1; 5+5x1; 5+3+2x1; 5+5
Output
66 66
{'plain': 2539, 'memo': 169}
CacheInfo(hits=72, misses=169, maxsize=None, currsize=169)

How it works:

  1. The recursion branches twice per call. Many branches reach the same (n, i), so the plain version repeats work: overlapping subproblems.
  2. @cache stores each (n, i) result. The memoized version computes each pair once; cache_info() shows how many calls were answered from the cache (hits).
  3. n can only take the values −4 to 40, and i the values 0 to 3, so at most 45×4=18045 \times 4 = 180 different (n, i) pairs exist. That bounds the memoized work: 169 calls computed something, and 72 were answered from the cache.
  4. The assert lists the 7 combinations for 10 pairs by hand, a quick sanity check of the recursion.

Alternative: a bottom-up table, the classic dynamic programming form, needs no recursion at all:

ways = [1] + [0] * 40
for size in SIZES:
for n in range(size, 41):
ways[n] += ways[n - size]
print(ways[40])
Output
66

Processing one pack size at a time makes the table count combinations, not ordered sequences.

M17-C15 · Choose a method: full sort or heap for the top 3

Section titled “M17-C15 · Choose a method: full sort or heap for the top 3”
Core

Choose a method and justify it: a report needs the 3 largest sales lines by revenue out of the 20,228 lines of data/sales.csv. Count the comparisons of sorted(revenues, reverse=True)[:3] and of heapq.nlargest(3, revenues), then decide which to use and why.

Expected output
top 3: [5196.0, 4596.0, 4596.0]
full sort: 224,285 comparisons
nlargest: 20,331 comparisons
Starter
with open("data/sales.csv", newline="") as f:
revenues = [float(row["revenue"]) for row in csv.DictReader(f)]
def counting_key() -> tuple[Callable[[float], Any], dict[str, int]]:
"""Return (key function, counter dict); the key counts comparisons."""
counter = {"n": 0}
def compare(a: float, b: float) -> int:
counter["n"] += 1
return (a > b) - (a < b)
return cmp_to_key(compare), counter
# TODO: count the comparisons of the full sort and of nlargest
Hint 1

Both sorted() and heapq.nlargest() accept key=. Pass the counting key to each and read the counter after the call.

Hint 2

nlargest compares each new value with the smallest of its 3 candidates. Most values lose that one comparison and are dropped.

Solution
with open("data/sales.csv", newline="") as f:
revenues = [float(row["revenue"]) for row in csv.DictReader(f)]
def counting_key() -> tuple[Callable[[float], Any], dict[str, int]]:
"""Return (key function, counter dict); the key counts comparisons."""
counter = {"n": 0}
def compare(a: float, b: float) -> int:
counter["n"] += 1
return (a > b) - (a < b)
return cmp_to_key(compare), counter
key, sort_count = counting_key()
top_by_sort = sorted(revenues, key=key, reverse=True)[:3]
key, heap_count = counting_key()
top_by_heap = heapq.nlargest(3, revenues, key=key)
print("top 3:", top_by_heap)
print(f"full sort: {sort_count['n']:,} comparisons")
print(f"nlargest: {heap_count['n']:,} comparisons")
assert top_by_sort == top_by_heap
assert heap_count["n"] < sort_count["n"] / 5
Output
top 3: [5196.0, 4596.0, 4596.0]
full sort: 224,285 comparisons
nlargest: 20,331 comparisons

How it works:

  1. Both methods give the same 3 values.
  2. The full sort orders all 20,228 values, O(nlog⁡n)O(n \log n), although the report uses only 3 of them.
  3. nlargest keeps a heap of 3. Each new value needs one comparison with the heap’s smallest; only the rare value that beats it costs a few more. That is close to nn comparisons.
  4. Decision: use heapq.nlargest. It does several times less work, needs O(k)O(k) memory instead of a full sorted copy, and also works on a stream that you read once. Use a full sort when you need most of the ranking, or many different top-k cuts of the same data.

Alternative: for k=1k = 1, use max(revenues): exactly n−1n - 1 comparisons. nlargest(1, ...) calls max() internally.

M17-X01 · A priority scheduler with retries

Section titled “M17-X01 · A priority scheduler with retries”
Challenge

A nightly job runner holds tasks in a priority queue: (priority, arrival, name), where a lower priority runs first and arrival breaks ties. When a task fails, the runner pushes it back with priority + 1 and a new arrival number, up to 2 retries; after that, it gives up. The failures are fixed: load_sales fails on its first attempt, train_model fails on every attempt. Print the run log and the final status.

Expected output
p0 check_disk attempt 1: ok
p1 load_sales attempt 1: FAIL
p1 load_stores attempt 1: ok
p2 train_model attempt 1: FAIL
p2 load_sales attempt 2: ok
p3 send_report attempt 1: ok
p3 train_model attempt 2: FAIL
p4 train_model attempt 3: FAIL
check_disk done after 1 attempt(s)
load_sales done after 2 attempt(s)
load_stores done after 1 attempt(s)
send_report done after 1 attempt(s)
train_model given up
Starter
from itertools import count
FAILS = {"load_sales": 1, "train_model": 99} # how many attempts fail
initial = [(1, "load_sales"), (0, "check_disk"), (2, "train_model"), (1, "load_stores"),
(3, "send_report")]
arrival = count()
queue: list[tuple[int, int, str, int]] = [] # (priority, arrival, name, attempt)
# TODO: push every task with attempt 1
# TODO: pop, "run", log, and re-push failures with priority + 1, at most 2 retries
Hint 1

A task fails when attempt <= FAILS.get(name, 0). Keep attempt in the tuple after the tie-breaker, so it is never compared before arrival.

Hint 2

On failure: if attempt <= 2, push (priority + 1, next(arrival), name, attempt + 1); otherwise record the task as given up.

Solution
from itertools import count
FAILS = {"load_sales": 1, "train_model": 99} # how many attempts fail
initial = [(1, "load_sales"), (0, "check_disk"), (2, "train_model"), (1, "load_stores"),
(3, "send_report")]
arrival = count()
queue: list[tuple[int, int, str, int]] = [] # (priority, arrival, name, attempt)
for priority, name in initial:
heapq.heappush(queue, (priority, next(arrival), name, 1))
status: dict[str, str] = {}
while queue:
priority, _, name, attempt = heapq.heappop(queue)
failed = attempt <= FAILS.get(name, 0)
result = "FAIL" if failed else "ok"
print(f"p{priority} {name:<12} attempt {attempt}: {result}")
if not failed:
status[name] = f"done after {attempt} attempt(s)"
elif attempt <= 2:
heapq.heappush(queue, (priority + 1, next(arrival), name, attempt + 1))
else:
status[name] = "given up"
for name in sorted(status):
print(f"{name:<12} {status[name]}")
assert status["train_model"] == "given up"
assert status["load_sales"] == "done after 2 attempt(s)"
Output
p0 check_disk attempt 1: ok
p1 load_sales attempt 1: FAIL
p1 load_stores attempt 1: ok
p2 train_model attempt 1: FAIL
p2 load_sales attempt 2: ok
p3 send_report attempt 1: ok
p3 train_model attempt 2: FAIL
p4 train_model attempt 3: FAIL
check_disk done after 1 attempt(s)
load_sales done after 2 attempt(s)
load_stores done after 1 attempt(s)
send_report done after 1 attempt(s)
train_model given up

How it works:

  1. All five tasks enter the heap with attempt 1. check_disk has priority 0 and runs first.
  2. load_sales and load_stores tie at priority 1; load_sales arrived first, so it runs first. It fails and returns with priority 2 and a new arrival number, behind train_model, which already waits at priority 2.
  3. train_model fails three times: at priorities 2, 3 and 4. After the third attempt, the runner gives up.
  4. The arrival counter makes the order fully deterministic, and it keeps Python from comparing names or attempts on ties.

Alternative: queue.PriorityQueue from the standard library wraps the same heapq calls with locks for threads (module 15). In a single thread, plain heapq is simpler and faster.

M17-X02 · Vibration incidents from overlapping windows

Section titled “M17-X02 · Vibration incidents from overlapping windows”
Challenge

Turn rolling alerts into incidents for sensor S4. A window of 6 consecutive readings (blank readings skipped) is an alert when its mean vibration is at least 4.5 mm/s. Overlapping or touching alert windows belong to the same incident. Report the number of incidents, the 3 longest ones (start, end, number of readings) and the number of short incidents: at most 11 readings, the footprint of a single spike.

Expected output
10 incidents
2024-05-12T05:40:00 to 2024-05-14T23:40:00: 397 readings
2024-05-01T07:10:00 to 2024-05-01T08:50:00: 11 readings
2024-05-02T17:30:00 to 2024-05-02T19:10:00: 11 readings
short incidents (<= 11 readings): 9
Starter
with open("data/sensors.csv", newline="") as f:
s4 = [(r["timestamp"], float(r["vibration_mm_s"])) for r in csv.DictReader(f)
if r["sensor_id"] == "S4" and r["vibration_mm_s"]]
K, LIMIT = 6, 4.5
incidents: list[list[int]] = [] # [first index, last index] of the readings
# TODO: running sum over windows of K readings
# TODO: for an alert window [i, i + K - 1]: extend the last incident or start a new one
Hint 1

Windows overlap or touch when the new window starts at or before last_end + 1. Then extend: incidents[-1][1] = i + K - 1.

Hint 2

The length of an incident in readings is end - start + 1. Sort the incidents by that length with heapq.nlargest(3, incidents, key=...).

Solution
with open("data/sensors.csv", newline="") as f:
s4 = [(r["timestamp"], float(r["vibration_mm_s"])) for r in csv.DictReader(f)
if r["sensor_id"] == "S4" and r["vibration_mm_s"]]
K, LIMIT = 6, 4.5
incidents: list[list[int]] = [] # [first index, last index] of the readings
window = sum(v for _, v in s4[:K])
for i in range(len(s4) - K + 1):
if i > 0:
window += s4[i + K - 1][1] - s4[i - 1][1]
if window / K >= LIMIT:
start, end = i, i + K - 1
if incidents and start <= incidents[-1][1] + 1:
incidents[-1][1] = end # overlaps or touches: extend
else:
incidents.append([start, end])
def length(inc: list[int]) -> int:
return inc[1] - inc[0] + 1
print(len(incidents), "incidents")
for start, end in heapq.nlargest(3, incidents, key=length):
print(f"{s4[start][0]} to {s4[end][0]}: {end - start + 1} readings")
short = sum(1 for inc in incidents if length(inc) <= 2 * K - 1)
print("short incidents (<= 11 readings):", short)
assert all(a[1] + 1 < b[0] for a, b in zip(incidents, incidents[1:]))
Output
10 incidents
2024-05-12T05:40:00 to 2024-05-14T23:40:00: 397 readings
2024-05-01T07:10:00 to 2024-05-01T08:50:00: 11 readings
2024-05-02T17:30:00 to 2024-05-02T19:10:00: 11 readings
short incidents (<= 11 readings): 9

How it works:

  1. The running sum gives each window mean in O(1)O(1): add the reading that enters, subtract the one that leaves.
  2. Windows arrive in order of their start index. So an alert window either extends the last incident (when it starts at or before one reading after its end) or starts a new one. This is the classic merge intervals step, done in the same pass.
  3. The longest incident is the wear period: 397 readings from May 12, 05:40 to the end of the data.
  4. One high reading at index s sits in the 6 windows that start at s - 5 to s. If all of them alert, they merge into one incident from s - 5 to s + 5: 11 readings. So an incident of at most 11 readings is the footprint of a single bad reading or a short burst. Here, 9 of the 10 incidents are short. Seven are spikes of 12.9 to 17.7 mm/s before May 12. The final assert checks that no two incidents overlap or touch.

Alternative: a median instead of a mean ignores single spikes: a 6-reading median needs at least 3 high readings. statistics.median over each window is O(k)O(k) per window, which is fine for k=6k = 6.

M17-X03 · Longest stable stretch of temperature

Section titled “M17-X03 · Longest stable stretch of temperature”
Challenge

Find the longest stretch of consecutive S1 temperature readings (blanks skipped) in which the highest and lowest readings differ by at most 0.5 °C. Use a variable-size sliding window with two monotonic deques, one for the window maximum and one for the minimum. Check the answer with a brute-force search on the first 300 readings.

Expected output
18 readings from 2024-05-13T00:40:00 to 2024-05-13T03:30:00
min 19.41, max 19.87
Starter
with open("data/sensors.csv", newline="") as f:
s1 = [(r["timestamp"], float(r["temperature_c"])) for r in csv.DictReader(f)
if r["sensor_id"] == "S1" and r["temperature_c"]]
temps = [t for _, t in s1]
def longest_stable(values: list[float], tol: float) -> tuple[int, int]:
"""Return (start, length) of the longest window with max - min <= tol."""
hi_q: deque[int] = deque() # indices, values decreasing: front is the max
lo_q: deque[int] = deque() # indices, values increasing: front is the min
left = 0
best = (0, 0)
# TODO: for each right index: update both deques, shrink from the left while
# max - min > tol, then record the window if it is the longest so far
return best
Hint 1

Before you append index right, pop from the back of hi_q every index whose value is <= the new value, and from lo_q every index whose value is >= it.

Hint 2

While values[hi_q[0]] - values[lo_q[0]] > tol: move left one step right, and pop the front of a deque when its index is less than left.

Solution
with open("data/sensors.csv", newline="") as f:
s1 = [(r["timestamp"], float(r["temperature_c"])) for r in csv.DictReader(f)
if r["sensor_id"] == "S1" and r["temperature_c"]]
temps = [t for _, t in s1]
def longest_stable(values: list[float], tol: float) -> tuple[int, int]:
"""Return (start, length) of the longest window with max - min <= tol."""
hi_q: deque[int] = deque() # indices, values decreasing: front is the max
lo_q: deque[int] = deque() # indices, values increasing: front is the min
left = 0
best = (0, 0)
for right, v in enumerate(values):
while hi_q and values[hi_q[-1]] <= v:
hi_q.pop()
hi_q.append(right)
while lo_q and values[lo_q[-1]] >= v:
lo_q.pop()
lo_q.append(right)
while values[hi_q[0]] - values[lo_q[0]] > tol:
left += 1
if hi_q[0] < left:
hi_q.popleft()
if lo_q[0] < left:
lo_q.popleft()
if right - left + 1 > best[1]:
best = (left, right - left + 1)
return best
def brute(values: list[float], tol: float) -> int:
return max(j - i + 1 for i in range(len(values)) for j in range(i, len(values))
if max(values[i : j + 1]) - min(values[i : j + 1]) <= tol)
start, n = longest_stable(temps, 0.5)
window = temps[start : start + n]
print(f"{n} readings from {s1[start][0]} to {s1[start + n - 1][0]}")
print(f"min {min(window)}, max {max(window)}")
assert max(window) - min(window) <= 0.5
assert longest_stable(temps[:300], 0.5)[1] == brute(temps[:300], 0.5)
Output
18 readings from 2024-05-13T00:40:00 to 2024-05-13T03:30:00
min 19.41, max 19.87

How it works:

  1. hi_q keeps indices with decreasing values, so its front is the window maximum; lo_q keeps increasing values, so its front is the minimum.
  2. Each new reading removes from the back of each deque the values it makes useless: a smaller old value can never be the maximum again while the new one is in the window.
  3. When the spread is too large, the left edge moves right. Indices that fall out of the window leave the deque fronts.
  4. Each index enters and leaves each deque at most once, so the whole search is O(n)O(n). The brute force is O(n3)O(n^3) and only runs on 300 readings to check the answer.
  5. The longest stable stretch falls in the night, when the daily temperature cycle is flat.

Alternative: a sorted list of the window values with insort and bisect removal also gives the min and max, at O(k)O(k) per step for the list shifts. The monotonic deques are faster and simpler for min and max; the sorted window is the tool when you need a rolling median.

M17-X04 · Flatten nested JSON without recursion

Section titled “M17-X04 · Flatten nested JSON without recursion”
Challenge

Flatten each customer record of data/customers.json into a dict with dotted keys, such as address.city and orders.0.amount. Write a recursive version and an iterative version with an explicit stack, and check that they agree on all 20 records. Then show why the iterative one matters: build a document nested 3,000 levels deep, which the recursive version cannot handle.

Expected output
True
address.city 'Chicago'
address.postal_code '81790'
address.region 'North'
address.street '546 Park Blvd'
customer_id 'C00001'
email 'ana.silva@example.com'
32 keys in the first record
recursive: RecursionError
iterative: 18005 characters in the key
Starter
def flatten_recursive(value: object, prefix: str = "") -> dict[str, object]:
# TODO: dicts and lists recurse with the extended prefix; anything else is a leaf
return {}
def flatten_iterative(value: object) -> dict[str, object]:
out: dict[str, object] = {}
stack: list[tuple[str, object]] = [("", value)]
# TODO: pop (prefix, value); push children of dicts and lists; store leaves
return out
with open("data/customers.json", encoding="utf-8") as f:
customers = json.load(f)["customers"]
# TODO: compare the two versions on all customers, then try a 3,000-level document
Hint 1

For a dict, the children are (f"{prefix}.{key}" if prefix else key, child). For a list, use the index as the key. An empty dict or list is a leaf too, so it does not disappear.

Hint 2

The iterative version visits keys in a different order. Compare the results as dicts, which ignore order, and sort the keys for printing.

Solution
def flatten_recursive(value: object, prefix: str = "") -> dict[str, object]:
if isinstance(value, (dict, list)) and value:
items = value.items() if isinstance(value, dict) else enumerate(value)
out: dict[str, object] = {}
for key, child in items:
path = f"{prefix}.{key}" if prefix else str(key)
out.update(flatten_recursive(child, path))
return out
return {prefix: value}
def flatten_iterative(value: object) -> dict[str, object]:
out: dict[str, object] = {}
stack: list[tuple[str, object]] = [("", value)]
while stack:
prefix, node = stack.pop()
if isinstance(node, (dict, list)) and node:
items = node.items() if isinstance(node, dict) else enumerate(node)
for key, child in items:
stack.append((f"{prefix}.{key}" if prefix else str(key), child))
else:
out[prefix] = node
return out
with open("data/customers.json", encoding="utf-8") as f:
customers = json.load(f)["customers"]
flat = [flatten_iterative(c) for c in customers]
print(all(f == flatten_recursive(c) for f, c in zip(flat, customers, strict=True)))
first = flat[0]
for key in sorted(first)[:6]:
print(f"{key:<20} {first[key]!r}")
print(len(first), "keys in the first record")
deep: dict = {}
node = deep
for _ in range(3_000):
node["child"] = {}
node = node["child"]
node["value"] = 1
try:
flatten_recursive(deep)
print("recursive: ok")
except RecursionError:
print("recursive: RecursionError")
print("iterative:", len(next(iter(flatten_iterative(deep)))), "characters in the key")
assert flatten_iterative(deep)[".".join(["child"] * 3_000) + ".value"] == 1
Output
True
address.city 'Chicago'
address.postal_code '81790'
address.region 'North'
address.street '546 Park Blvd'
customer_id 'C00001'
email 'ana.silva@example.com'
32 keys in the first record
recursive: RecursionError
iterative: 18005 characters in the key

How it works:

  1. Both versions treat a non-empty dict or list as a branch and everything else (including {} and []) as a leaf. Empty tags and orders lists stay visible as keys with the value [].
  2. The recursive version uses the call stack; the iterative one keeps (prefix, value) pairs in a list and pops them. Same logic, different stack.
  3. The iterative version visits children in reverse order, because a stack is LIFO. The dict comparison ignores the order, so both versions agree on all 20 records.
  4. The deep document needs 3,001 nested calls. Python stops at its recursion limit of 1,000 and raises RecursionError. The list-based stack grows to any depth.
  5. Real JSON is rarely that deep. But data from users can be, and a service that flattens untrusted input must not crash on it.

Alternative: pandas.json_normalize(customers, sep=".") flattens nested dicts into DataFrame columns (module 24). It keeps lists such as orders as one cell; pass record_path="orders" to explode them into rows.

M17-X05 · A stable merge sort for records

Section titled “M17-X05 · A stable merge sort for records”
Challenge

Write merge_sort(records, key) that returns a new list sorted by key(record), is stable, and counts its comparisons. Test it on the first 1,000 lines of data/sales.csv sorted by category: the result must equal sorted(..., key=...) exactly, including the order of lines inside each category. Then compare its comparison count with Timsort’s on the same task.

Expected output
identical to sorted(): True
first Books lines: ['O000005', 'O000009', 'O000010', 'O000018']
merge sort: 8,300 | Timsort: 6,105 comparisons
Starter
with open("data/sales.csv", newline="") as f:
lines = list(islice(csv.DictReader(f), 1000))
Row = dict[str, str]
def merge_sort(
records: list[Row], key: Callable[[Row], str], counter: list[int]
) -> list[Row]:
# TODO: split, sort both halves, merge with <= on the keys (that keeps it stable)
return records[:]
Hint 1

Compute key(record) in the merge step, compare with <=, and take from the left half on ties. Taking from the right half on ties would break stability.

Hint 2

To count Timsort’s comparisons with a key, wrap the key: cmp_to_key(lambda a, b: compare(key(a), key(b))), with a compare that counts its calls.

Solution
with open("data/sales.csv", newline="") as f:
lines = list(islice(csv.DictReader(f), 1000))
Row = dict[str, str]
def merge_sort(
records: list[Row], key: Callable[[Row], str], counter: list[int]
) -> list[Row]:
if len(records) <= 1:
return records[:]
mid = len(records) // 2
left = merge_sort(records[:mid], key, counter)
right = merge_sort(records[mid:], key, counter)
merged: list[Row] = []
i = j = 0
while i < len(left) and j < len(right):
counter[0] += 1
if key(left[i]) <= key(right[j]): # ties take the left: stable
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
return merged + left[i:] + right[j:]
category = itemgetter("category")
counter = [0]
mine = merge_sort(lines, category, counter)
timsort_calls = 0
def compare(a: Row, b: Row) -> int:
global timsort_calls
timsort_calls += 1
ka, kb = category(a), category(b)
return (ka > kb) - (ka < kb)
reference = sorted(lines, key=cmp_to_key(compare))
print("identical to sorted():", mine == reference)
books = [r["order_id"] for r in mine if r["category"] == "Books"]
print("first Books lines:", books[:4])
print(f"merge sort: {counter[0]:,} | Timsort: {timsort_calls:,} comparisons")
assert mine == sorted(lines, key=category)
assert [r["order_id"] for r in mine] != [r["order_id"] for r in lines]
Output
identical to sorted(): True
first Books lines: ['O000005', 'O000009', 'O000010', 'O000018']
merge sort: 8,300 | Timsort: 6,105 comparisons

How it works:

  1. The merge compares the keys of the two fronts. On a tie, it takes the left element, which came first in the input. So equal keys keep their input order at every level: the sort is stable.
  2. mine == reference compares the full records in order. With only 6 categories, almost every comparison is a tie, so any instability would show at once.
  3. Merge sort always splits in halves, about nlog⁡2n≈10,000n \log_2 n \approx 10{,}000 comparisons in the worst case. Timsort finds runs and uses binary insertion on short stretches, so it needs fewer.
  4. The order ids inside the Books category ascend, because the input is in order id order and both sorts keep it.

Alternative: sorted(lines, key=category) is the right tool in real code. Write merge sort when you must sort data that does not fit in memory: sort chunks, write them to files, and merge the files with heapq.merge. This is an external sort.

M17-X06 · Find comparable houses with bisect and two pointers

Section titled “M17-X06 · Find comparable houses with bisect and two pointers”
Challenge

An appraiser values a house by its comparables: the 5 sales in data/houses.csv with prices closest to an asking price of 500,000. Find them with bisect_left on the sorted prices, then expand two pointers outward, always taking the closer side (the lower price on a tie). Count the steps and check against a full sort by distance.

Expected output
H2312 Riverside 499,500 2030 sqft
H0537 Westfield 500,500 1040 sqft
H0947 Maple Grove 500,500 2530 sqft
H1993 Old Town 500,500 2290 sqft
H2640 Maple Grove 500,500 1990 sqft
steps: 5
Starter
with open("data/houses.csv", newline="") as f:
houses = sorted(csv.DictReader(f), key=lambda h: int(h["price"]))
prices = [int(h["price"]) for h in houses]
target, k = 500_000, 5
# TODO: right = bisect_left(prices, target); left = right - 1
# TODO: take k houses, each time from the side whose price is closer to target
Hint 1

left moves down and right moves up. When one side runs off the list, take from the other side.

Hint 2

The left side is closer when target - prices[left] <= prices[right] - target. The <= gives ties to the lower price.

Solution
with open("data/houses.csv", newline="") as f:
houses = sorted(csv.DictReader(f), key=lambda h: int(h["price"]))
prices = [int(h["price"]) for h in houses]
target, k = 500_000, 5
right = bisect_left(prices, target)
left = right - 1
chosen: list[int] = []
steps = 0
while len(chosen) < k:
steps += 1
take_left = right >= len(prices) or (
left >= 0 and target - prices[left] <= prices[right] - target
)
if take_left:
chosen.append(left)
left -= 1
else:
chosen.append(right)
right += 1
for i in sorted(chosen):
h = houses[i]
price = int(h["price"])
print(f"{h['house_id']} {h['neighborhood']:<12} {price:>9,} {h['sqft']:>5} sqft")
print("steps:", steps)
by_distance = sorted(
range(len(prices)), key=lambda i: (abs(prices[i] - target), prices[i])
)
assert sorted(prices[i] for i in chosen) == sorted(prices[i] for i in by_distance[:k])
Output
H2312 Riverside 499,500 2030 sqft
H0537 Westfield 500,500 1040 sqft
H0947 Maple Grove 500,500 2530 sqft
H1993 Old Town 500,500 2290 sqft
H2640 Maple Grove 500,500 1990 sqft
steps: 5

How it works:

  1. bisect_left finds where 500,000 would go: everything left of it is cheaper, everything from it on is at least 500,000. The comparables sit around that point.
  2. Two pointers start at the two neighbors of the insertion point. Each step takes the closer one and moves that pointer outward. The two candidates are always the closest unused prices on each side.
  3. After the sort, the search is O(log⁡n+k)O(\log n + k): about 12 comparisons for the bisect plus 5 steps. The check sorts all 3,000 houses by distance, O(nlog⁡n)O(n \log n).
  4. Several houses can share a price (prices are multiples of 500), so the assert compares the chosen prices, not the house ids.
  5. Look at H0537: 1,040 sqft in Westfield at 500,500. It is one of the injected price outliers of the dataset, priced like a house twice its size. Comparables by price alone can mislead; a real appraisal also matches size and neighborhood.

Alternative: heapq.nsmallest(k, houses, key=lambda h: abs(int(h["price"]) - target)) finds the same prices in one line, in O(nlog⁡k)O(n \log k) and without a sort. Use it for one question; use the sorted list and bisect when many appraisals query the same data.