Skip to content

10. Iterators and generators — Exercises

These exercises practice every idea of the Iterators and generators lesson. They stream the real course files: data/sales.csv, data/sensors.csv, data/reports/ and data/logs/app.log.

How to work:

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

Each solution ends with assert checks. Add the same checks to your own code.

Every exercise on this page starts with these imports and the read_rows() source generator from the lesson. Paste the block at the top of each script.

import csv
from collections import Counter, defaultdict, deque
from collections.abc import Iterable, Iterator
from itertools import batched, islice
def read_rows(path: str) -> Iterator[dict[str, str]]:
"""Yield each row of a CSV file as a dict of strings."""
with open(path, encoding="utf-8", newline="") as f:
yield from csv.DictReader(f)
Warm-up

The three sensor statuses are ["ok", "warn", "fail"]. Get an iterator over the list and print the three items with next(). Then ask for a fourth item so that it prints done instead of raising StopIteration.

Expected output
ok
warn
fail
done
Starter
statuses = ["ok", "warn", "fail"]
# TODO: get an iterator with iter()
# TODO: print three items with next()
# TODO: print a fourth item with a default of "done"
Hint 1

The list holds the data; you need a second object that remembers a position in it. Which built-in function asks a list for one?

Hint 2

it = iter(statuses) gives the iterator, and next(it) returns one item. next() also accepts a second argument: the value to return when the iterator is used up.

Solution
statuses = ["ok", "warn", "fail"]
it = iter(statuses)
first = next(it)
second = next(it)
third = next(it)
fourth = next(it, "done")
print(first)
print(second)
print(third)
print(fourth)
assert [first, second, third] == statuses
assert fourth == "done"
assert next(it, None) is None # still exhausted
Output
ok
warn
fail
done

How it works:

  1. iter(statuses) returns a list_iterator that points before the first item.
  2. Each next(it) returns the next item and moves the position.
  3. After "fail", the iterator is exhausted. next(it, "done") returns the default instead of raising StopIteration.

Alternative: catch the exception yourself. This is what a for loop does.

it = iter(["ok", "warn", "fail"])
try:
for _ in range(4):
print(next(it))
except StopIteration:
print("done")
Output
ok
warn
fail
done
Warm-up

Predict the output: read the code and write down, line by line, what it prints. Then run it.

Starter
def stages() -> Iterator[str]:
print("load")
yield "rows"
print("clean")
yield "clean rows"
print("save")
g = stages()
print("start")
for item in g:
print("got", item)
print("end")

Acceptance criteria:

  • Write your prediction line by line before you run the code.
  • Your prediction matches the Output in the solution, in the same order.
Hint 1

Calling stages() runs none of its body.

Hint 2

Each next() (here, each loop step) runs the body only up to the next yield. The loop asks one more time after the last item, and that request runs the rest of the body.

Solution
import inspect
def stages() -> Iterator[str]:
print("load")
yield "rows"
print("clean")
yield "clean rows"
print("save")
g = stages()
print("start")
for item in g:
print("got", item)
print("end")
assert inspect.getgeneratorstate(g) == "GEN_CLOSED"
Output
start
load
got rows
clean
got clean rows
save
end

How it works:

  1. g = stages() creates the generator. Nothing prints, so start comes first.
  2. The first loop step runs the body to yield "rows": load prints, then the loop prints got rows.
  3. The second step resumes after the first yield: clean, then got clean rows.
  4. The third step resumes again, prints save and reaches the end of the body. The generator raises StopIteration, and the loop ends before end prints.
Warm-up

The first reading of each sensor in data/sensors.csv is [20.21, 22.3, 19.4, 24.52] °C. Write a generator function to_fahrenheit(celsius) that yields each value in °F (°F = °C × 9 / 5 + 32), rounded to 1 decimal. Print the converted list.

Expected output
[68.4, 72.1, 66.9, 76.1]
Starter
def to_fahrenheit(celsius: Iterable[float]) -> Iterator[float]:
# TODO: yield each value converted and rounded
...
first_readings = [20.21, 22.3, 19.4, 24.52]
# TODO: print the list of converted values
Hint 1

Loop over celsius and yield one value per item.

Hint 2

list(to_fahrenheit(first_readings)) consumes the generator and builds the list to print.

Solution
def to_fahrenheit(celsius: Iterable[float]) -> Iterator[float]:
for c in celsius:
yield round(c * 9 / 5 + 32, 1)
first_readings = [20.21, 22.3, 19.4, 24.52]
converted = list(to_fahrenheit(first_readings))
print(converted)
assert len(converted) == len(first_readings)
assert converted[1] == 72.1
Output
[68.4, 72.1, 66.9, 76.1]

How it works:

  1. The yield makes to_fahrenheit a generator function. Calling it returns a generator.
  2. list() calls next() until the generator ends, and collects the four values.
  3. The type hints say: the function takes any iterable of floats and returns an iterator of floats.

Alternative: a generator expression does the same in one line: (round(c * 9 / 5 + 32, 1) for c in first_readings). Use the function form when the logic needs more than one expression.

Warm-up

The first five lines of data/sales.csv are typed in below, with only three of their columns. Order O000004 has two lines. Use generator expressions inside sum() to compute the total quantity and the number of lines with a discount. Do not build any list.

Expected output
units: 5
discounted lines: 2
Starter
lines = [
{"order_id": "O000001", "quantity": 1, "discount": 0.05},
{"order_id": "O000002", "quantity": 1, "discount": 0.0},
{"order_id": "O000003", "quantity": 1, "discount": 0.0},
{"order_id": "O000004", "quantity": 1, "discount": 0.0},
{"order_id": "O000004", "quantity": 1, "discount": 0.1},
]
# TODO: total quantity with sum() and a generator expression
# TODO: number of discounted lines
Hint 1

As the only argument of a call, a generator expression needs no extra parentheses: sum(x for x in items).

Hint 2

To count, sum 1 for each item that passes a condition: sum(1 for line in lines if ...).

Solution
lines = [
{"order_id": "O000001", "quantity": 1, "discount": 0.05},
{"order_id": "O000002", "quantity": 1, "discount": 0.0},
{"order_id": "O000003", "quantity": 1, "discount": 0.0},
{"order_id": "O000004", "quantity": 1, "discount": 0.0},
{"order_id": "O000004", "quantity": 1, "discount": 0.1},
]
units = sum(line["quantity"] for line in lines)
discounted = sum(1 for line in lines if line["discount"] > 0)
print("units:", units)
print("discounted lines:", discounted)
assert units == 5
assert discounted == 2
Output
units: 5
discounted lines: 2

How it works:

  1. sum(line["quantity"] for line in lines) passes a generator to sum(), which pulls one quantity at a time.
  2. sum(1 for ... if ...) adds 1 for each line that passes the filter, which counts them.
  3. No list of quantities exists at any point.

Alternative: True counts as 1, so sum(line["discount"] > 0 for line in lines) also counts. The 1 for ... if form says the intent more clearly.

Warm-up

Fix the bug: this code should print the count and the mean of four readings from data/readings.txt. It prints a mean of 0.0. Find the cause and fix it with the smallest change.

Expected output
count: 4
mean: 21.5
Starter
raw = ["21.0", "21.9", "21.4", "21.7"]
temps = map(float, raw)
count = len(list(temps))
mean = sum(temps) / count
print("count:", count)
print("mean:", round(mean, 2))
Hint 1

map() returns an iterator. How many times can you loop over an iterator?

Hint 2

list(temps) consumed every value. Keep that list and use it twice.

Solution
raw = ["21.0", "21.9", "21.4", "21.7"]
temps = list(map(float, raw)) # store the values once
count = len(temps)
mean = sum(temps) / count
print("count:", count)
print("mean:", round(mean, 2))
assert count == 4
assert round(mean, 2) == 21.5
Output
count: 4
mean: 21.5

How it works:

  1. In the bug, list(temps) exhausted the map iterator, so sum(temps) added nothing and returned 0.
  2. The fix stores the values in a list once. A list is re-iterable, so len() and sum() both see all four values.
  3. Four values are small, so a list is the right choice here.

Alternative: for a big stream, compute both in one pass: count = total = 0, then a loop that adds 1 and the value.

Warm-up

A colleague asks about lines 101 to 103 of data/sales.csv (counting data rows from 1, without the header). Print the order_id and product of these three lines. Use islice on the read_rows() stream. Do not build a list of all rows.

Expected output
O000074 Trail Running Shoes
O000075 Air Purifier
O000076 A Brief History of Maps
Starter
rows = read_rows("data/sales.csv")
# TODO: islice the stream to data rows 101..103
# TODO: print order_id and product of each
Hint 1

islice(it, start, stop) uses 0-based positions and a half-open range, like range().

Hint 2

Row 101 has position 100. You want positions 100, 101 and 102.

Solution
rows = read_rows("data/sales.csv")
selected = list(islice(rows, 100, 103))
for row in selected:
print(row["order_id"], row["product"])
assert len(selected) == 3
assert all(row["order_date"].startswith("2023-01") for row in selected)
Output
O000074 Trail Running Shoes
O000075 Air Purifier
O000076 A Brief History of Maps

How it works:

  1. islice(rows, 100, 103) reads and drops the first 100 rows, then yields 3 rows and stops.
  2. The source stops after row 103. The rest of the file is never read.
  3. The list holds only the three selected rows.

Alternative: enumerate(rows, start=1) with an if 101 <= n <= 103 test also works, but it reads the whole file unless you add a break.

M10-W07 · Flatten batches with yield from

Section titled “M10-W07 · Flatten batches with yield from”
Warm-up

The stores arrive grouped by region. Write a generator flatten(groups) that yields every store id of every group, in order, with yield from. Print the result as a list.

Expected output
['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08']
Starter
regions = [["S01", "S02", "S03"], ["S04", "S05", "S06"], ["S07", "S08"]]
def flatten(groups: Iterable[list[str]]) -> Iterator[str]:
# TODO: yield every item of every group
...
# TODO: print the flattened list
Hint 1

One loop over the groups is enough. Inside it, delegate to the group.

Hint 2

yield from group yields each item of group.

Solution
regions = [["S01", "S02", "S03"], ["S04", "S05", "S06"], ["S07", "S08"]]
def flatten(groups: Iterable[list[str]]) -> Iterator[str]:
for group in groups:
yield from group
flat = list(flatten(regions))
print(flat)
assert len(flat) == 8
assert flat[3] == "S04"
Output
['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08']

How it works:

  1. The outer loop takes one group at a time.
  2. yield from group hands each store id of the group to the caller before the loop moves on.
  3. It is short for for store in group: yield store.

Alternative: itertools.chain.from_iterable(regions) does the same without a function.

from itertools import chain
print(list(chain.from_iterable(regions)))
Output
['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08']
Warm-up

A stock API accepts at most 5 store ids per call. Split the 12 store ids S01 to S12 into batches with itertools.batched and print one line per call.

Expected output
call 1: S01 S02 S03 S04 S05
call 2: S06 S07 S08 S09 S10
call 3: S11 S12
Starter
store_ids = [f"S{n:02d}" for n in range(1, 13)]
# TODO: loop over batches of 5 and print "call N: id id ..."
Hint 1

batched(store_ids, 5) yields tuples of up to 5 ids.

Hint 2

enumerate(..., start=1) numbers the calls. " ".join(batch) joins one tuple of ids.

Solution
store_ids = [f"S{n:02d}" for n in range(1, 13)]
calls = []
for number, batch in enumerate(batched(store_ids, 5), start=1):
print(f"call {number}: {' '.join(batch)}")
calls.append(batch)
assert [len(b) for b in calls] == [5, 5, 2]
assert calls[-1] == ("S11", "S12")
Output
call 1: S01 S02 S03 S04 S05
call 2: S06 S07 S08 S09 S10
call 3: S11 S12

How it works:

  1. batched(store_ids, 5) yields (S01, …, S05), (S06, …, S10) and the rest, (S11, S12).
  2. enumerate adds a call number, starting at 1.
  3. Each batch is a tuple, so the assert compares with a tuple.

Alternative: without batched (Python 3.11 and older), slice the list in steps: for i in range(0, len(store_ids), 5): batch = store_ids[i:i + 5]. This works only for lists, not for streams.

Warm-up

Choose a method and justify it: for each task, decide whether a list comprehension or a generator expression fits better. Then run your choice.

  1. Total revenue of data/sales.csv.
  2. The 12 store floor areas in square feet (1 m² = 10.764 sq ft), used three times: smallest, largest and total.
  3. Is any temperature in data/sensors.csv at 42 °C or above (the fail limit)?
Expected output
total revenue: 3,596,523.83
sq ft min, max, total: 14531 36598 282340
any reading >= 42 °C: True
Starter
sizes_sqm = [2850, 1950, 1420, 3100, 2300, 1680, 3400, 2050, 1760, 2480, 1890, 1350]
# TODO 1: total revenue
# TODO 2: floor areas in sq ft; print min, max and total
# TODO 3: any temperature >= 42 (skip blank cells)
Hint 1

Ask two questions per task: do I need the values more than once, or in a new order? Is the input big?

Hint 2

A generator gives its values once; three uses need three passes. any() stops at the first True.

Solution
sizes_sqm = [2850, 1950, 1420, 3100, 2300, 1680, 3400, 2050, 1760, 2480, 1890, 1350]
# 1. One pass over a big file: generator expression.
total = sum(float(r["revenue"]) for r in read_rows("data/sales.csv"))
# 2. Small data, used three times: list.
sizes_sqft = [round(s * 10.764) for s in sizes_sqm]
# 3. Big file, can stop early: generator expression in any().
hot = any(
float(r["temperature_c"]) >= 42
for r in read_rows("data/sensors.csv")
if r["temperature_c"]
)
print(f"total revenue: {total:,.2f}")
print("sq ft min, max, total:", min(sizes_sqft), max(sizes_sqft), sum(sizes_sqft))
print("any reading >= 42 °C:", hot)
assert round(total, 2) == 3596523.83
assert len(sizes_sqft) == 12
assert hot
Output
total revenue: 3,596,523.83
sq ft min, max, total: 14531 36598 282340
any reading >= 42 °C: True

How it works:

  1. The revenue total reads each row once and keeps nothing, so a generator expression fits.
  2. min(), max() and sum() each loop over the values. A generator would be empty after min(). The data has 12 items, so a list costs nothing.
  3. any() returns at the first reading at or above 42 °C. With a generator, the rest of the file is never parsed. With a list comprehension, all 8,064 rows would be parsed first.

Alternative: for task 2 on a big stream, compute the minimum, maximum and total in one loop instead of storing the values.

M10-C01 · Write a date-range iterator class

Section titled “M10-C01 · Write a date-range iterator class”
Core

Write an iterator class DateRange(start, end) that yields every datetime.date from start to end, both included. Use it to print the first three days of 2024 and the number of days in 2024 (the sales period’s leap year).

Expected output
['2024-01-01', '2024-01-02', '2024-01-03']
days in 2024: 366
Starter
from datetime import date, timedelta
from typing import Self
class DateRange:
def __init__(self, start: date, end: date) -> None:
# TODO: store the state
...
def __iter__(self) -> Self:
# TODO
...
def __next__(self) -> date:
# TODO: return the current date and move on, or raise StopIteration
...
# TODO: print the first three dates of 2024 and the number of days in 2024
Hint 1

What must the object remember between two next() calls? Store that in __init__. An iterator’s __iter__ has only one job.

Hint 2

__next__ has two cases: past the end (signal the end of the iteration) or not (return a date and move the position by timedelta(days=1)). Return the date before you move.

Hint 3

Count with sum(1 for _ in DateRange(...)). Use a new object for the count, because the first one is partly used.

Solution
from datetime import date, timedelta
from typing import Self
class DateRange:
"""Iterator over the dates from start to end, both included."""
def __init__(self, start: date, end: date) -> None:
self.current = start
self.end = end
def __iter__(self) -> Self:
return self
def __next__(self) -> date:
if self.current > self.end:
raise StopIteration
day = self.current
self.current += timedelta(days=1)
return day
year = DateRange(date(2024, 1, 1), date(2024, 12, 31))
print([d.isoformat() for d in islice(year, 3)])
days_2024 = sum(1 for _ in DateRange(date(2024, 1, 1), date(2024, 12, 31)))
print("days in 2024:", days_2024)
assert days_2024 == 366
assert next(year) == date(2024, 1, 4) # the first object kept its position
Output
['2024-01-01', '2024-01-02', '2024-01-03']
days in 2024: 366

How it works:

  1. __init__ stores the position (current) and the stop date.
  2. __iter__ returns the object itself, which makes it an iterator.
  3. __next__ returns one date per call and raises StopIteration after end.
  4. islice(year, 3) took three dates. The last assert shows that year remembers its position: the next date is January 4.

Alternative: a generator function is shorter and does the same job:

def date_range(start: date, end: date) -> Iterator[date]:
day = start
while day <= end:
yield day
day += timedelta(days=1)
print(sum(1 for _ in date_range(date(2023, 1, 1), date(2024, 12, 31))))
Output
731

The sales period has 731 days, the number of distinct dates in data/sales.csv.

M10-C02 · Make the date range re-iterable

Section titled “M10-C02 · Make the date range re-iterable”
Core

Refactor: the one-pass DateRange iterator from C01 breaks this report, because the second loop gets nothing. Change the class so that every loop sees all the dates. Keep the class name and its constructor. The report counts the days of the 2024 summer sale week (July 14–20) and lists the weekend days.

Expected output
days: 7
weekend: ['2024-07-14', '2024-07-20']
Starter
from datetime import date, timedelta
from typing import Self
class DateRange:
def __init__(self, start: date, end: date) -> None:
self.current = start
self.end = end
def __iter__(self) -> Self:
return self
def __next__(self) -> date:
if self.current > self.end:
raise StopIteration
day = self.current
self.current += timedelta(days=1)
return day
week = DateRange(date(2024, 7, 14), date(2024, 7, 20))
print("days:", sum(1 for _ in week))
print("weekend:", [d.isoformat() for d in week if d.weekday() >= 5])
Hint 1

An iterable that is not an iterator returns a new iterator from __iter__ each time.

Hint 2

Make __iter__ a generator: put the date loop inside it with yield. Then delete __next__. Store start, not current.

Solution
from datetime import date, timedelta
class DateRange:
"""Re-iterable range of dates from start to end, both included."""
def __init__(self, start: date, end: date) -> None:
self.start = start
self.end = end
def __iter__(self) -> Iterator[date]:
day = self.start
while day <= self.end:
yield day
day += timedelta(days=1)
week = DateRange(date(2024, 7, 14), date(2024, 7, 20))
days = sum(1 for _ in week)
weekend = [d.isoformat() for d in week if d.weekday() >= 5]
print("days:", days)
print("weekend:", weekend)
assert days == 7
assert weekend == ["2024-07-14", "2024-07-20"]
assert iter(week) is not iter(week) # a fresh iterator each time
Output
days: 7
weekend: ['2024-07-14', '2024-07-20']

How it works:

  1. The object now stores only start and end, which never change.
  2. __iter__ contains yield, so each call returns a new generator that starts at start.
  3. sum() and the list comprehension each call iter(week) and get their own generator, so both see 7 days.
  4. weekday() is 5 for Saturday and 6 for Sunday. July 14, 2024 was a Sunday.

Alternative: keep the iterator class and add a separate iterable class whose __iter__ returns DateRangeIterator(self.start, self.end). That is the classic two-class design (like list and list_iterator). The generator form needs half the code.

Core

Store S12 (Denver) opened during the sales period. In one pass over data/sales.csv, compute its number of lines, its total revenue and its first sales date. Use a filter generator expression and one loop. Do not build a list of rows.

Expected output
S12: 868 lines, revenue 152,673.29, first sale 2023-06-15
Starter
s12 = ... # TODO: generator expression of S12 rows
lines = 0
revenue = 0.0
first_date = None
# TODO: one loop that updates the three results
# TODO: print the report
Hint 1

(r for r in read_rows("data/sales.csv") if r["store_id"] == "S12") is the filter.

Hint 2

The file is sorted by date, so the first S12 row has the first date. Set first_date only while it is still None.

Solution
s12 = (r for r in read_rows("data/sales.csv") if r["store_id"] == "S12")
lines = 0
revenue = 0.0
first_date = None
for row in s12:
lines += 1
revenue += float(row["revenue"])
if first_date is None:
first_date = row["order_date"]
print(f"S12: {lines} lines, revenue {revenue:,.2f}, first sale {first_date}")
assert lines == 868
assert first_date == "2023-06-15"
assert abs(revenue - 152673.29) < 0.01
Output
S12: 868 lines, revenue 152,673.29, first sale 2023-06-15

How it works:

  1. The generator expression passes on only S12 rows, one at a time.
  2. One loop updates three results, so the file is read once.
  3. Because data/sales.csv is sorted by date, the first S12 row is its opening day: 2023-06-15, as in data/stores.csv.

Alternative: next(r["order_date"] for r in ... if r["store_id"] == "S12") finds the first date and stops reading at that row. It is the fastest way to find a first match, but it needs a second pass for the totals.

Core

The warehouse wants every bulk line: a sales line with 10 or more units. Write a generator bulk_lines(rows, min_qty=10) that yields (order_id, product, quantity) tuples. Print how many bulk lines exist and the three largest by quantity (ties: in file order).

Expected output
bulk lines: 29
O003982 25 x Slim Fit Jeans
O008005 25 x Weeknight Kitchen Cookbook
O010887 25 x Slim Fit Jeans
Starter
def bulk_lines(
rows: Iterable[dict[str, str]], min_qty: int = 10
) -> Iterator[tuple[str, str, int]]:
# TODO: yield (order_id, product, quantity) for big lines
...
# TODO: collect the bulk lines, print the count and the top 3
Hint 1

Convert row["quantity"] with int() once, then compare.

Hint 2

The result is small (a few dozen lines), so a list of it is fine. sorted(..., key=lambda line: line[2], reverse=True) keeps ties in their original order, because Python’s sort is stable.

Solution
def bulk_lines(
rows: Iterable[dict[str, str]], min_qty: int = 10
) -> Iterator[tuple[str, str, int]]:
for row in rows:
quantity = int(row["quantity"])
if quantity >= min_qty:
yield row["order_id"], row["product"], quantity
bulk = list(bulk_lines(read_rows("data/sales.csv")))
print("bulk lines:", len(bulk))
for order_id, product, quantity in sorted(bulk, key=lambda b: b[2], reverse=True)[:3]:
print(f"{order_id} {quantity:>2} x {product}")
assert len(bulk) == 29
assert all(q >= 10 for _, _, q in bulk)
Output
bulk lines: 29
O003982 25 x Slim Fit Jeans
O008005 25 x Weeknight Kitchen Cookbook
O010887 25 x Slim Fit Jeans

How it works:

  1. The generator streams the 20,228 rows and passes on only the 29 bulk lines.
  2. Storing the 29 results in a list is cheap, and it allows len() and sorting.
  3. sorted() with reverse=True puts the biggest quantities first. A stable sort keeps equal quantities in file order.

Alternative: heapq.nlargest(3, bulk_lines(...), key=lambda b: b[2]) keeps only 3 items in memory, even on a stream of millions. It is the streaming way to find a top N.

Core

Process data/sales.csv in chunks of 5,000 lines. For each chunk, print its number, its first date, its number of lines and its mean line revenue. Is revenue per line rising over time?

Expected output
chunk 1: from 2023-01-01, 5000 lines, mean 179.85
chunk 2: from 2023-08-19, 5000 lines, mean 181.35
chunk 3: from 2024-02-14, 5000 lines, mean 167.31
chunk 4: from 2024-08-18, 5000 lines, mean 181.24
chunk 5: from 2024-12-27, 228 lines, mean 209.56
Starter
for number, chunk in enumerate(batched(read_rows("data/sales.csv"), 5_000), start=1):
# TODO: first date, size and mean revenue of the chunk
...
Hint 1

A chunk is a tuple of row dicts, so chunk[0] is its first row and len(chunk) its size.

Hint 2

statistics.fmean() takes any iterable of numbers, including a generator expression.

Solution
from statistics import fmean
means = []
chunks = enumerate(batched(read_rows("data/sales.csv"), 5_000), start=1)
for number, chunk in chunks:
mean_revenue = fmean(float(r["revenue"]) for r in chunk)
means.append(mean_revenue)
print(f"chunk {number}: from {chunk[0]['order_date']}, {len(chunk):>5} lines,"
f" mean {mean_revenue:6.2f}")
assert len(means) == 5
Output
chunk 1: from 2023-01-01, 5000 lines, mean 179.85
chunk 2: from 2023-08-19, 5000 lines, mean 181.35
chunk 3: from 2024-02-14, 5000 lines, mean 167.31
chunk 4: from 2024-08-18, 5000 lines, mean 181.24
chunk 5: from 2024-12-27, 228 lines, mean 209.56

How it works:

  1. batched groups the stream into tuples of 5,000 rows. The fifth chunk holds the last 228.
  2. Inside one chunk, indexing and len() work, because a chunk is a tuple.
  3. The mean does not rise steadily: it moves with the season, and the small last chunk is the end of December. Chunks of equal row counts cover unequal time spans, so for a trend, group by month instead.

Alternative: pandas does the same with pd.read_csv("data/sales.csv", chunksize=5_000), which yields DataFrames. Compute chunk["revenue"].mean() for each.

Core

Fix the bug: this chunked() function should give Python 3.11 code the behavior of itertools.batched (3.12+). On a list it never ends: it yields the first chunk again and again (press Ctrl+C to stop it). Fix it so that it works on lists and on streams, and check it against batched on 23 order ids in chunks of 5.

Expected output
5 O000001
5 O000006
5 O000011
5 O000016
3 O000021
Starter
def chunked(iterable: Iterable[str], n: int) -> Iterator[list[str]]:
while chunk := list(islice(iterable, n)):
yield chunk
order_ids = [f"O{n:06d}" for n in range(1, 24)]
for chunk in chunked(order_ids, 5): # never ends
print(len(chunk), chunk[0])
Hint 1

What does islice(a_list, 5) return the first time, and the second time?

Hint 2

islice on a list creates a new iterator from position 0 every time. Create one iterator before the loop and slice that.

Solution
def chunked(iterable: Iterable[str], n: int) -> Iterator[list[str]]:
"""Yield lists of up to n items; works on lists and streams."""
it = iter(iterable) # one shared position
while chunk := list(islice(it, n)):
yield chunk
order_ids = [f"O{n:06d}" for n in range(1, 24)]
for chunk in chunked(order_ids, 5):
print(len(chunk), chunk[0])
ours = [tuple(c) for c in chunked(order_ids, 5)]
assert ours == list(batched(order_ids, 5))
assert sum(1 for _ in chunked(read_rows("data/sales.csv"), 5_000)) == 5
Output
5 O000001
5 O000006
5 O000011
5 O000016
3 O000021

How it works:

  1. A list is iterable but not an iterator. Each islice(order_ids, 5) called iter() on the list again and started from the top.
  2. it = iter(iterable) creates one iterator. Every islice(it, 5) continues where the last one stopped.
  3. On a stream (an iterator), iter() returns the same object, so the function works for both.
  4. The := operator stores the chunk and tests it. An empty list ends the loop.

Alternative: on Python 3.12+, use itertools.batched(iterable, n). It does exactly this and yields tuples.

Core

Write a generator humidity_readings(rows, skipped) that yields (sensor_id, humidity) with humidity as a float. It skips rows with a blank humidity_pct and counts them per sensor in the skipped Counter. Use it to print the mean humidity per sensor (1 decimal) and the skipped counts.

Expected output
S1: mean 55.0 %, skipped 11
S2: mean 55.0 %, skipped 8
S3: mean 51.3 %, skipped 5
S4: mean 55.2 %, skipped 5
Starter
def humidity_readings(
rows: Iterable[dict[str, str]], skipped: Counter[str]
) -> Iterator[tuple[str, float]]:
# TODO: skip and count blank cells, yield (sensor_id, float)
...
skipped: Counter[str] = Counter()
sums: defaultdict[str, float] = defaultdict(float)
counts: Counter[str] = Counter()
# TODO: one loop over the generator; then print the means and skipped
Hint 1

A blank cell is the empty string "", which is falsy.

Hint 2

Keep a running sum and a count per sensor in the loop; divide at the end. Print skipped only after the loop.

Solution
def humidity_readings(
rows: Iterable[dict[str, str]], skipped: Counter[str]
) -> Iterator[tuple[str, float]]:
for row in rows:
if not row["humidity_pct"]:
skipped[row["sensor_id"]] += 1
continue
yield row["sensor_id"], float(row["humidity_pct"])
skipped: Counter[str] = Counter()
sums: defaultdict[str, float] = defaultdict(float)
counts: Counter[str] = Counter()
for sensor_id, humidity in humidity_readings(read_rows("data/sensors.csv"), skipped):
sums[sensor_id] += humidity
counts[sensor_id] += 1
for sensor_id in sorted(sums):
print(f"{sensor_id}: mean {sums[sensor_id] / counts[sensor_id]:.1f} %,"
f" skipped {skipped[sensor_id]}")
assert skipped.total() == 29
assert counts.total() + skipped.total() == 8064
Output
S1: mean 55.0 %, skipped 11
S2: mean 55.0 %, skipped 8
S3: mean 51.3 %, skipped 5
S4: mean 55.2 %, skipped 5

How it works:

  1. if not row["humidity_pct"] catches the empty string. The generator counts the gap and moves on with continue.
  2. The sink keeps a running sum and count per sensor, so memory holds 4 sums and 4 counts.
  3. skipped is complete only after the loop, because the generator fills it while it runs.
  4. The 29 skipped cells match the data dictionary.

Alternative: yield None for blanks instead of skipping them, and let the sink decide. This keeps the row count intact, which matters when timestamps must line up.

Core

Sensor S3 drifts upward by about 0.35 °C per day. Stream data/sensors.csv, keep only S3 rows with a temperature, and use groupby on the date part of the timestamp to compute the daily mean. Print the first two and the last two days, and the change per day from the first day to the last.

Expected output
2024-05-01 21.29
2024-05-02 21.60
2024-05-13 25.34
2024-05-14 25.85
14 days, drift +0.35 °C per day
Starter
from itertools import groupby
from statistics import fmean
s3 = ... # TODO: generator of (date, temperature) for S3 rows with a temperature
daily = ... # TODO: list of (date, mean) with groupby
# TODO: print the first two and last two days, and the drift per day
Hint 1

The date is the first 10 characters of the timestamp: row["timestamp"][:10].

Hint 2

The file is sorted by timestamp, so after the S3 filter the dates are still in order and groupby gives one group per day. The key function receives a (date, temperature) pair.

Hint 3

Drift per day = (last mean − first mean) / (number of days − 1).

Solution
from itertools import groupby
from statistics import fmean
s3 = (
(row["timestamp"][:10], float(row["temperature_c"]))
for row in read_rows("data/sensors.csv")
if row["sensor_id"] == "S3" and row["temperature_c"]
)
daily = [
(day, fmean(t for _, t in group))
for day, group in groupby(s3, key=lambda pair: pair[0])
]
for day, mean in daily[:2] + daily[-2:]:
print(day, f"{mean:.2f}")
drift = (daily[-1][1] - daily[0][1]) / (len(daily) - 1)
print(f"{len(daily)} days, drift {drift:+.2f} °C per day")
assert len(daily) == 14
assert 0.3 < drift < 0.4
Output
2024-05-01 21.29
2024-05-02 21.60
2024-05-13 25.34
2024-05-14 25.85
14 days, drift +0.35 °C per day

How it works:

  1. The generator expression filters to S3, skips blanks and keeps only the date and the temperature.
  2. groupby groups consecutive pairs with the same date. It works because the file is sorted by time.
  3. Inside the comprehension, each group is consumed by fmean before groupby moves on.
  4. The 14 daily means fit in a list. The 2,016 S3 readings never did.

Alternative: a defaultdict(list) keyed by date also works, but it stores every reading. Use groupby when the data is sorted by the key; it holds one group at a time.

Core

Sensor S4 wears out near the end of the log. Compute the rolling mean of its vibration_mm_s over the last 6 readings (one hour), skipping blank cells. Print the first timestamp where the rolling mean reaches the warn level of 4.5 mm/s, and the highest rolling mean of the log.

Expected output
first rolling mean >= 4.5: 2024-05-01T08:00:00
highest rolling mean: 10.53 mm/s
Starter
from statistics import fmean
window: deque[float] = deque(maxlen=6)
first_warn = None
highest = 0.0
# TODO: loop over S4 rows with a vibration value; update the window and results
Hint 1

A deque(maxlen=6) drops the oldest value when you append a seventh.

Hint 2

Compute the mean only when len(window) == 6. Record the first timestamp with if first_warn is None and mean >= 4.5.

Solution
from statistics import fmean
window: deque[float] = deque(maxlen=6)
first_warn = None
highest = 0.0
s4 = (
r
for r in read_rows("data/sensors.csv")
if r["sensor_id"] == "S4" and r["vibration_mm_s"]
)
for row in s4:
window.append(float(row["vibration_mm_s"]))
if len(window) < 6:
continue
mean = fmean(window)
highest = max(highest, mean)
if first_warn is None and mean >= 4.5:
first_warn = row["timestamp"]
print("first rolling mean >= 4.5:", first_warn)
print(f"highest rolling mean: {highest:.2f} mm/s")
assert first_warn is not None
assert first_warn == "2024-05-01T08:00:00"
Output
first rolling mean >= 4.5: 2024-05-01T08:00:00
highest rolling mean: 10.53 mm/s

How it works:

  1. The generator expression keeps only S4 rows with a vibration value.
  2. The deque holds the last 6 values; fmean averages them.
  3. The first hour-long mean at the warn level marks the start of the trouble. A single high reading would not, because the rolling mean smooths it out.

Interpretation: the first crossing is early in the log. A single vibration spike (×3 to ×5) lifts the hour-long mean above 4.5 for a short time. To detect wear rather than spikes, use a longer window or a rolling median, which ignores single outliers.

Alternative: turn the window logic into a reusable generator rolling_mean(values, 6), as in the lesson, and feed it the vibration values.

M10-C10 · Refactor an eager script into a pipeline

Section titled “M10-C10 · Refactor an eager script into a pipeline”
Core

Refactor: this script computes the 2023 Electronics revenue of the online channel and of the store channel. It reads the whole file with readlines(), splits each line by hand and makes one full list pass per channel. Rewrite it as a lazy pipeline: a csv.DictReader source, a parse stage that yields (channel, revenue) for the 2023 Electronics lines, and one sink loop that fills both totals in a single pass. The results must not change.

Expected output
online 339,645.97
store 528,537.43
Starter
def eager() -> dict[str, float]:
with open("data/sales.csv", encoding="utf-8") as f:
lines = f.readlines()[1:] # every line in memory; skip the header
fields = [line.rstrip("\n").split(",") for line in lines]
online = sum(
float(x[12]) for x in fields
if x[1].startswith("2023") and x[8] == "Electronics" and x[5] == "online"
)
store = sum(
float(x[12]) for x in fields
if x[1].startswith("2023") and x[8] == "Electronics" and x[5] == "store"
)
return {"online": online, "store": store}
def lazy() -> dict[str, float]:
# TODO: DictReader source, a parse/filter generator, one sink loop
...
Hint 1

Three things change: where the rows come from, how a column is found, and how many times the data is read. Tackle them one by one.

Hint 2

read_rows() from the setup gives dicts, so x[12] becomes row["revenue"]. A generator stage can apply both conditions and yield only the channel and the revenue.

Hint 3

In the sink, totals: defaultdict[str, float] = defaultdict(float) and totals[channel] += revenue handle both channels in one loop.

Solution
import math
def eager() -> dict[str, float]:
with open("data/sales.csv", encoding="utf-8") as f:
lines = f.readlines()[1:] # every line in memory; skip the header
fields = [line.rstrip("\n").split(",") for line in lines]
online = sum(
float(x[12])
for x in fields
if x[1].startswith("2023") and x[8] == "Electronics" and x[5] == "online"
)
store = sum(
float(x[12])
for x in fields
if x[1].startswith("2023") and x[8] == "Electronics" and x[5] == "store"
)
return {"online": online, "store": store}
def electronics_2023(rows: Iterable[dict[str, str]]) -> Iterator[tuple[str, float]]:
"""Parse and filter: (channel, revenue) of the 2023 Electronics lines."""
for row in rows:
if row["order_date"].startswith("2023") and row["category"] == "Electronics":
yield row["channel"], float(row["revenue"])
def lazy() -> dict[str, float]:
totals: defaultdict[str, float] = defaultdict(float)
for channel, revenue in electronics_2023(read_rows("data/sales.csv")):
totals[channel] += revenue # one pass fills both channels
return dict(totals)
before, after = eager(), lazy()
for channel in sorted(after):
print(f"{channel:<7}{after[channel]:>12,.2f}")
assert after.keys() == before.keys()
assert all(math.isclose(before[c], after[c]) for c in before)
Output
online 339,645.97
store 528,537.43

How it works:

  1. Source. read_rows() streams dicts instead of loading every line with readlines().
  2. Names, not positions. row["revenue"] replaces x[12]. The code no longer breaks when a column moves, and it is correct even if a field contains a quoted comma, which split(",") would cut in two.
  3. One pass. The eager script scanned the list twice, once per channel. The defaultdict sink fills both totals in one loop, and it would handle a third channel with no new code.
  4. The asserts compare the two versions channel by channel with math.isclose, because floats summed in a different order can differ in the last digit.

Alternative: Counter also sums floats: Counter() with totals[channel] += revenue works the same, and totals.most_common() ranks the channels.

Core

Fix the bug and interpret the result: this report should print the number of lines for each of the 12 stores. It prints far more groups than stores. Explain why, then fix it without sorting the file.

Expected output
groupby groups: 13493
stores: 12
S01 2220
S02 1563
S03 1183
Starter
from itertools import groupby
groups = groupby(read_rows("data/sales.csv"), key=lambda r: r["store_id"])
counts = [(store, sum(1 for _ in lines)) for store, lines in groups]
print("groups:", len(counts)) # expected 12
Hint 1

groupby starts a new group every time the key changes from one row to the next. What is the file sorted by?

Hint 2

A Counter counts per key in one pass, whatever the order.

Solution
from itertools import groupby
groups = groupby(read_rows("data/sales.csv"), key=lambda r: r["store_id"])
print("groupby groups:", sum(1 for _ in groups))
per_store = Counter(r["store_id"] for r in read_rows("data/sales.csv"))
print("stores:", len(per_store))
for store, lines in sorted(per_store.items())[:3]:
print(store, lines)
assert len(per_store) == 12
assert per_store["S01"] == 2220
Output
groupby groups: 13493
stores: 12
S01 2220
S02 1563
S03 1183

How it works:

  1. The file is sorted by date, not by store. Consecutive lines come from different stores, so the key changes almost every line and groupby makes almost one group per line.
  2. A Counter adds 1 per store whatever the order. It holds 12 counts.
  3. The counts match the stores table of the data dictionary: S01 has 2,220 lines.

Interpretation: groupby is the right tool only when the stream is sorted by the key, such as dates in this file. For any other key, use a dict-based sink, or sort first if the data fits in memory.

Core

Predict the output: this code splits one stream with tee and also uses the original iterator by mistake. Write down what each line prints, then run it.

Starter
from itertools import tee
readings = iter([20.21, 20.22, 20.16, 19.93, 19.9])
left, right = tee(readings)
print(next(left), next(left))
print(next(readings))
print(list(right))
print(list(left))

Acceptance criteria:

  • Write your prediction line by line before you run the code.
  • Explain which value each copy loses, and why.
  • Your prediction matches the Output in the solution.
Hint 1

tee reads from readings only when a copy needs an item that no copy has seen yet. It stores the items that one copy has taken and the other has not.

Hint 2

After left took two items, tee has read 20.21 and 20.22 and stores them for right. The original’s next item is 20.16.

Solution
from itertools import tee
readings = iter([20.21, 20.22, 20.16, 19.93, 19.9])
left, right = tee(readings)
print(next(left), next(left))
print(next(readings))
rest_right = list(right)
rest_left = list(left)
print(rest_right)
print(rest_left)
assert 20.16 not in rest_right + rest_left
assert rest_right[:2] == [20.21, 20.22]
Output
20.21 20.22
20.16
[20.21, 20.22, 19.93, 19.9]
[19.93, 19.9]

How it works:

  1. left took 20.21 and 20.22. tee read them from readings and stored them for right.
  2. next(readings) took 20.16 straight from the source. tee never saw it, so both copies lose it.
  3. right first gets the two stored values, then 19.93 and 19.9 from the source. left gets only 19.93 and 19.9.
  4. Lesson: after tee, never touch the original iterator.

M10-C13 · Units per category across monthly files

Section titled “M10-C13 · Units per category across monthly files”
Core

Stream all six files in data/reports/ as one sequence with chain.from_iterable and compute the units sold per category in the first half of 2024. Print the categories from most to fewest units. Remember that 2024-04.csv has its columns in another order.

Expected output
Beauty 83
Sports 82
Electronics 76
Clothing 74
Books 52
Home 42
total 409
Starter
from itertools import chain
from pathlib import Path
paths = sorted(Path("data/reports").glob("2024-*.csv"))
all_rows = ... # TODO: one stream over every file
units: Counter[str] = Counter()
# TODO: add the quantity of each row to its category; print the ranking
Hint 1

read_rows(path) streams one file. A generator expression (read_rows(p) for p in paths) is a stream of streams.

Hint 2

Counter.most_common() returns (key, count) pairs from the largest count down.

Solution
from itertools import chain
from pathlib import Path
paths = sorted(Path("data/reports").glob("2024-*.csv"))
all_rows = chain.from_iterable(read_rows(str(p)) for p in paths)
units: Counter[str] = Counter()
for row in all_rows:
units[row["category"]] += int(row["quantity"])
for category, n in units.most_common():
print(f"{category:<12}{n:>4}")
print(f"{'total':<12}{units.total():>4}")
assert len(units) == 6
Output
Beauty 83
Sports 82
Electronics 76
Clothing 74
Books 52
Home 42
total 409

How it works:

  1. chain.from_iterable takes the generator of six read_rows() streams and yields their rows one after another. Each file opens only when the chain reaches it.
  2. DictReader maps each value to its column name, so April’s different column order changes nothing.
  3. most_common() sorts the categories by units, largest first.

Alternative: a generator with a loop and yield from read_rows(p) gives the same stream. Use chain.from_iterable when a one-line expression is enough.

Challenge

Build a small ETL job (extract, transform, load: the classic three steps of a data pipeline). Extract data/sales.csv as a stream. Transform: keep the 2024 online lines and keep only order_date, category and revenue (as a float). Load the lines into an in-memory SQLite table online_2024 in batches of 1,000. Then query the revenue per category from the table and check the grand total against a second, pure-Python streaming pass.

Expected output
batches: 6
Electronics 1046 427,426.51
Home 825 181,857.19
Sports 851 143,396.72
Clothing 1011 79,829.48
Beauty 767 37,994.15
Books 650 26,109.36
total 896,613.41
Starter
import sqlite3
def extract(path: str) -> Iterator[dict[str, str]]:
... # TODO
def transform(rows: Iterable[dict[str, str]]) -> Iterator[tuple[str, str, float]]:
... # TODO: 2024 online lines -> (order_date, category, revenue)
def load(con: sqlite3.Connection, records: Iterable[tuple[str, str, float]]) -> int:
... # TODO: insert in batches of 1,000; return the number of batches
# TODO: run the job, query revenue per category, check the total
Hint 1

extract can simply return read_rows(path). transform is one loop with an if and a yield.

Hint 2

In load, loop over batched(records, 1_000) and make one executemany call per batch, with one ? placeholder per column.

Hint 3

Let SQL do the report: GROUP BY the category and ORDER BY the revenue sum, largest first. For the check, stream the file again through transform and compare the two totals with math.isclose.

Solution
import math
import sqlite3
def extract(path: str) -> Iterator[dict[str, str]]:
return read_rows(path)
def transform(rows: Iterable[dict[str, str]]) -> Iterator[tuple[str, str, float]]:
for row in rows:
if row["channel"] == "online" and row["order_date"].startswith("2024"):
yield row["order_date"], row["category"], float(row["revenue"])
def load(con: sqlite3.Connection, records: Iterable[tuple[str, str, float]]) -> int:
batches = 0
for batch in batched(records, 1_000):
con.executemany("INSERT INTO online_2024 VALUES (?, ?, ?)", batch)
batches += 1
con.commit()
return batches
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE online_2024 (order_date TEXT, category TEXT, revenue REAL)")
batches = load(con, transform(extract("data/sales.csv")))
query = (
"SELECT category, COUNT(*), ROUND(SUM(revenue), 2) FROM online_2024"
" GROUP BY category ORDER BY 3 DESC"
)
print("batches:", batches)
for category, lines, revenue in con.execute(query):
print(f"{category:<12}{lines:>6}{revenue:>14,.2f}")
(db_total,) = con.execute("SELECT SUM(revenue) FROM online_2024").fetchone()
check = sum(r for _, _, r in transform(extract("data/sales.csv")))
print(f"{'total':<12}{'':>6}{db_total:>14,.2f}")
con.close()
assert math.isclose(db_total, check)
assert batches == 6
Output
batches: 6
Electronics 1046 427,426.51
Home 825 181,857.19
Sports 851 143,396.72
Clothing 1011 79,829.48
Beauty 767 37,994.15
Books 650 26,109.36
total 896,613.41

How it works:

  1. Extract returns the lazy read_rows() stream. Nothing is read yet.
  2. Transform filters and reshapes one row at a time into small tuples.
  3. Load pulls the stream in batches of 1,000 and inserts each with one executemany call. The 5,150 online lines of 2024 need 6 calls.
  4. The SQL query aggregates inside the database. The second pass recomputes the total in Python, and the assert compares the two. Production ETL jobs end with exactly this kind of reconciliation: a check that the target holds the same counts and totals as the source.

Alternative: skip the database and aggregate in a defaultdict sink. The database pays off when other tools query the loaded table later.

M10-X02 · Detect vibration spikes per sensor

Section titled “M10-X02 · Detect vibration spikes per sensor”
Challenge

The data dictionary says that 41 vibration readings were multiplied by 3 to 5. Build a detector: for each sensor, keep the median of its last 6 vibration readings (skip blanks) and flag a reading that is more than 2.5 times that median. Keep spikes out of the window. Print the spike count per sensor and in total, and the first three spikes. Why is a median better than a mean here?

Expected output
{'S1': 7, 'S2': 10, 'S3': 12, 'S4': 10} total 39
2024-05-01T08:00:00 S4 12.92 mm/s vs median 3.05
2024-05-02T00:20:00 S1 7.53 mm/s vs median 2.21
2024-05-02T10:10:00 S1 7.53 mm/s vs median 1.86
Starter
from statistics import median
def vibration_spikes(
rows: Iterable[dict[str, str]], window: int = 6, factor: float = 2.5
) -> Iterator[tuple[str, str, float, float]]:
"""Yield (timestamp, sensor_id, value, baseline) for each spike."""
# TODO: one deque per sensor; compare with the median; keep spikes out
...
# TODO: count per sensor, print the totals and the first three spikes
Hint 1

defaultdict(lambda: deque(maxlen=window)) creates one window per sensor on first use.

Hint 2

When the window is full and value > factor * median(window), yield the spike and continue without appending. Otherwise append the value.

Hint 3

To print the first three spikes and count all of them in one pass, collect the spikes in a list. There are only a few dozen, so the list is small.

Solution
from statistics import median
def vibration_spikes(
rows: Iterable[dict[str, str]], window: int = 6, factor: float = 2.5
) -> Iterator[tuple[str, str, float, float]]:
"""Yield (timestamp, sensor_id, value, baseline) for each spike."""
recent: defaultdict[str, deque[float]] = defaultdict(lambda: deque(maxlen=window))
for row in rows:
if not row["vibration_mm_s"]:
continue
value = float(row["vibration_mm_s"])
values = recent[row["sensor_id"]]
if len(values) == window:
baseline = median(values)
if value > factor * baseline:
yield row["timestamp"], row["sensor_id"], value, baseline
continue
values.append(value)
spikes = list(vibration_spikes(read_rows("data/sensors.csv")))
per_sensor = Counter(sensor for _, sensor, _, _ in spikes)
print(dict(sorted(per_sensor.items())), "total", len(spikes))
for ts, sensor, value, baseline in spikes[:3]:
print(f"{ts} {sensor} {value:5.2f} mm/s vs median {baseline:.2f}")
assert len(spikes) == per_sensor.total()
assert 35 <= len(spikes) <= 45
Output
{'S1': 7, 'S2': 10, 'S3': 12, 'S4': 10} total 39
2024-05-01T08:00:00 S4 12.92 mm/s vs median 3.05
2024-05-02T00:20:00 S1 7.53 mm/s vs median 2.21
2024-05-02T10:10:00 S1 7.53 mm/s vs median 1.86

How it works:

  1. One deque per sensor holds its last 6 normal readings. The defaultdict creates each on first use.
  2. The median of 6 values is the mean of the middle two after sorting. One extreme value in the window barely moves it.
  3. A spike is yielded and kept out of the window, so the baseline stays clean.
  4. The spikes are few, so collecting them in a list is cheap; the 8,064 rows were never stored.

Interpretation: the detector finds about as many spikes as were injected (41). A mean would be pulled up by any spike or by the wear of S4 that the window still holds, and would then miss the next spike. The median ignores single outliers, which is why robust statistics (measures that single outliers barely move, such as the median) are the default for anomaly detection.

Alternative: use a z-score: flag values more than 4 rolling standard deviations above the rolling mean (statistics.fmean and statistics.stdev). It adapts to noisy sensors but needs a longer window to be stable.

M10-X03 · Summarize a log file with a pipeline

Section titled “M10-X03 · Summarize a log file with a pipeline”
Challenge

data/logs/app.log has 500 lines. Normal lines start with a timestamp: 2024-05-01 08:04:01,354 INFO [api] message. Eight lines belong to two multi-line tracebacks and do not start with a digit. Build a pipeline of generators: read lines, skip and count the traceback lines, parse each line into (level, component, message). Then print the count per level and the three slowest API requests (the api messages end with a duration such as 87ms, followed by a user field).

Expected output
skipped traceback lines: 8
levels: {'INFO': 447, 'WARNING': 25, 'DEBUG': 13, 'ERROR': 7}
1334 ms GET /api/v1/products?page=2
1188 ms POST /api/v1/predict
974 ms GET /api/v1/products?page=2
Starter
import heapq
def read_lines(path: str) -> Iterator[str]:
... # TODO: yield each line without its newline
def skip_tracebacks(lines: Iterable[str], skipped: list[int]) -> Iterator[str]:
... # TODO: yield lines that start with a digit; count the others in skipped[0]
def parse(lines: Iterable[str]) -> Iterator[tuple[str, str, str]]:
... # TODO: (level, component, message)
# TODO: one pass that counts levels and keeps the three slowest api requests
Hint 1

line.split(" ", 4) splits a normal line into date, time, level, [component] and the message. strip("[]") removes the brackets.

Hint 2

An API message looks like 10.0.3.17 GET /api/v1/reports/2024-04 200 87ms user=.... message.split() gives six fields; the fifth is the duration, and int(duration.removesuffix("ms")) converts it.

Hint 3

heapq.nlargest(3, iterable, key=...) keeps only 3 items while it streams. Feed it a generator of (ms, method, path) tuples. Since you also need the level counts, collect the API tuples in a small list during the single pass, or count levels inside a generator stage.

Solution
import heapq
def read_lines(path: str) -> Iterator[str]:
with open(path, encoding="utf-8") as f:
for line in f:
yield line.rstrip("\n")
def skip_tracebacks(lines: Iterable[str], skipped: list[int]) -> Iterator[str]:
for line in lines:
if line[:1].isdigit():
yield line
else:
skipped[0] += 1
def parse(lines: Iterable[str]) -> Iterator[tuple[str, str, str]]:
for line in lines:
_date, _time, level, component, message = line.split(" ", 4)
yield level, component.strip("[]"), message
def count_levels(
records: Iterable[tuple[str, str, str]], levels: Counter[str]
) -> Iterator[tuple[str, str, str]]:
for record in records:
levels[record[0]] += 1
yield record
def api_request(message: str) -> tuple[int, str, str]:
"""(duration in ms, method, path) of an API request message."""
_ip, method, path, _status, duration, _user = message.split()
return int(duration.removesuffix("ms")), method, path
skipped = [0]
levels: Counter[str] = Counter()
lines = skip_tracebacks(read_lines("data/logs/app.log"), skipped)
records = count_levels(parse(lines), levels)
requests = (api_request(msg) for _, component, msg in records if component == "api")
slowest = heapq.nlargest(3, requests)
print("skipped traceback lines:", skipped[0])
print("levels:", dict(levels.most_common()))
for ms, method, path in slowest:
print(f"{ms:>5} ms {method:<4} {path}")
assert levels.total() + skipped[0] == 500
assert levels["INFO"] == 447
assert len(slowest) == 3
Output
skipped traceback lines: 8
levels: {'INFO': 447, 'WARNING': 25, 'DEBUG': 13, 'ERROR': 7}
1334 ms GET /api/v1/products?page=2
1188 ms POST /api/v1/predict
974 ms GET /api/v1/products?page=2

How it works:

  1. read_lines streams the file. skip_tracebacks passes on lines that start with a digit and counts the rest in a one-item list, which the generator can change in place.
  2. parse splits each line at most 4 times, so the message keeps its spaces.
  3. count_levels is a pass-through stage: it counts each record and yields it unchanged. This gives a side result without a second pass.
  4. api_request unpacks the six fields of a request message. heapq.nlargest consumes the stream of API tuples and keeps only the top 3. Tuples compare by their first item, the duration.
  5. Every sink result is complete after nlargest has drained the stream.

Alternative: module 09’s regular expressions parse each line with one pattern and catch malformed lines more strictly. The pipeline shape stays the same.

M10-X04 · Longest problem streak per sensor

Section titled “M10-X04 · Longest problem streak per sensor”
Challenge

A streak (or run) is a sequence of consecutive readings with the same value. For each sensor, find the longest streak of readings whose status is not ok, its length and its start time. Use groupby on each sensor’s stream. Which sensor needs maintenance, and why does the streak tell you more than the raw count of warn rows?

Expected output
S1: 14 problem readings, longest streak 1 from 2024-05-02T00:20:00
S2: 22 problem readings, longest streak 1 from 2024-05-01T00:40:00
S3: 22 problem readings, longest streak 1 from 2024-05-01T10:40:00
S4: 419 problem readings, longest streak 272 from 2024-05-13T02:40:00
Starter
from itertools import groupby
def sensor_statuses(sensor_id: str) -> Iterator[tuple[str, str]]:
... # TODO: (timestamp, status) of one sensor, in time order
def longest_problem_streak(statuses: Iterable[tuple[str, str]]) -> tuple[int, str]:
... # TODO: (length, start timestamp) of the longest run of non-ok statuses
# TODO: print one line per sensor
Hint 1

Group by status != "ok", not by the status itself, so that a warn followed by a fail counts as one problem streak.

Hint 2

Each group is an iterator. To get its length and its first timestamp, take the first item with next() and count the rest with 1 + sum(1 for _ in group).

Hint 3

max(streaks, key=lambda s: s[0]) finds the longest streak; on a tie, it keeps the first one. Add default=(0, "-") for a sensor without problems.

Solution
from itertools import groupby
def sensor_statuses(sensor_id: str) -> Iterator[tuple[str, str]]:
for row in read_rows("data/sensors.csv"):
if row["sensor_id"] == sensor_id:
yield row["timestamp"], row["status"]
def problem_streaks(statuses: Iterable[tuple[str, str]]) -> Iterator[tuple[int, str]]:
"""Yield (length, start timestamp) of each run of non-ok statuses."""
for is_problem, group in groupby(statuses, key=lambda s: s[1] != "ok"):
if is_problem:
start, _ = next(group)
yield 1 + sum(1 for _ in group), start
def longest_problem_streak(statuses: Iterable[tuple[str, str]]) -> tuple[int, str]:
return max(problem_streaks(statuses), key=lambda s: s[0], default=(0, "-"))
results = {}
for sensor_id in ["S1", "S2", "S3", "S4"]:
problems = sum(1 for _, status in sensor_statuses(sensor_id) if status != "ok")
length, start = longest_problem_streak(sensor_statuses(sensor_id))
results[sensor_id] = length
print(f"{sensor_id}: {problems:>3} problem readings, longest streak {length:>3}"
f" from {start}")
assert max(results, key=results.get) == "S4"
Output
S1: 14 problem readings, longest streak 1 from 2024-05-02T00:20:00
S2: 22 problem readings, longest streak 1 from 2024-05-01T00:40:00
S3: 22 problem readings, longest streak 1 from 2024-05-01T10:40:00
S4: 419 problem readings, longest streak 272 from 2024-05-13T02:40:00

How it works:

  1. sensor_statuses streams one sensor’s (timestamp, status) pairs in time order.
  2. groupby(..., key=lambda s: s[1] != "ok") splits the stream into alternating runs of normal and problem readings.
  3. problem_streaks handles each problem run: next(group) takes the first reading (its start time), and sum(1 for _ in group) counts the rest. Each group is used before groupby moves on.
  4. max(..., key=...) keeps the longest run. No stage stores more than one reading.
  5. The cost: two passes per sensor, so the loop reads data/sensors.csv 8 times. That is fine for 8,064 rows, but it breaks the one-pass rule of this module for big logs; see the alternative.

Interpretation: S4 has by far the most problem readings and the longest streak. Scattered single warnings (S1 to S3) usually come from spikes. A long unbroken streak means the sensor stays out of range, which is the signature of wear and a reason to send a technician.

Alternative: one pass for all sensors. Keep a dict of per-sensor state (current run length, its start, best run, problem count). For each row, extend or reset that sensor’s current run and update its best run. It reads the file once but needs more state variables than groupby.

M10-X05 · Top orders from a line-level stream

Section titled “M10-X05 · Top orders from a line-level stream”
Challenge

data/sales.csv has one row per order line; an order has 1 to 3 lines. The rows of one order are consecutive, because the file is sorted by date and then order_id. Without loading the file, find the five orders with the highest total revenue. Print the order id, the date, the number of lines and the total.

Expected output
O001531 2023-04-24 lines=1 5,196.00
O014369 2024-12-17 lines=2 4,975.98
O011849 2024-09-25 lines=1 4,596.00
O006934 2024-01-14 lines=1 4,596.00
O006473 2023-12-23 lines=2 4,526.18
orders: 14877
Starter
import heapq
from itertools import groupby
def orders(rows: Iterable[dict[str, str]]) -> Iterator[tuple[float, str, str, int]]:
... # TODO: (total, order_id, order_date, lines) per order
# TODO: the five largest orders with heapq.nlargest
Hint 1

groupby(rows, key=lambda r: r["order_id"]) gives one group per order, because the lines of an order are consecutive.

Hint 2

Inside the group loop, materialize the group with list(group): an order has at most 3 lines, so this is cheap, and you need its length, its date and its sum.

Solution
import heapq
from itertools import groupby
def orders(rows: Iterable[dict[str, str]]) -> Iterator[tuple[float, str, str, int]]:
"""Yield (total, order_id, order_date, lines) for each order."""
for order_id, group in groupby(rows, key=lambda r: r["order_id"]):
lines = list(group) # 1-3 lines: small
total = round(sum(float(r["revenue"]) for r in lines), 2)
yield total, order_id, lines[0]["order_date"], len(lines)
all_orders = orders(read_rows("data/sales.csv"))
top = heapq.nlargest(5, all_orders)
for total, order_id, order_date, n_lines in top:
print(f"{order_id} {order_date} lines={n_lines} {total:>10,.2f}")
order_count = sum(1 for _ in orders(read_rows("data/sales.csv")))
print("orders:", order_count)
assert order_count == 14877
assert top[0][1] == "O001531"
Output
O001531 2023-04-24 lines=1 5,196.00
O014369 2024-12-17 lines=2 4,975.98
O011849 2024-09-25 lines=1 4,596.00
O006934 2024-01-14 lines=1 4,596.00
O006473 2023-12-23 lines=2 4,526.18
orders: 14877

How it works:

  1. groupby on order_id turns the line stream into an order stream, one order at a time.
  2. Each order is at most 3 lines, so list(group) is safe. The stage yields a tuple whose first item is the total.
  3. heapq.nlargest(5, ...) keeps a heap of the 5 best tuples while it streams 14,877 orders. Tuples compare by their first item, so the heap ranks by total.
  4. The order count matches the data dictionary (14,877 orders), which proves that groupby saw each order as one group.

Alternative: sorted(all_orders, reverse=True)[:5] gives the same result, but it stores all 14,877 orders first.

M10-X06 · Resume a load from a high-water mark

Section titled “M10-X06 · Resume a load from a high-water mark”
Challenge

A nightly job processes data/sales.csv in batches of 2,000 lines. After each batch, it saves its progress: a high-water mark: the number of lines processed so far, the point to resume from. Simulate a crash after batch 3. Then resume from the saved mark, finish the file, and prove that the two runs together processed every line exactly once and give the full revenue total.

Expected output
crash after line 6,000; revenue so far 1,076,852.90
resumed and finished: 20,228 lines, revenue 3,596,523.83
Starter
from typing import NamedTuple
class Progress(NamedTuple):
done: int # the high-water mark: lines processed so far
revenue: float
def run(start: Progress, max_batches: int | None) -> Progress:
"""Process batches of 2,000 lines after the first start.done lines.
Stop after max_batches batches (None = until the end); return the progress.
"""
# TODO: islice to skip, batched to chunk, islice to stop after max_batches
...
# TODO: first run from Progress(0, 0.0) crashes after 3 batches; print the mark
# TODO: second run resumes from the returned progress; print the final state
Hint 1

islice(rows, skip, None) skips the first skip lines and yields the rest.

Hint 2

islice(batched(...), max_batches) stops after max_batches batches. islice(it, None) means “no limit”.

Hint 3

Update the mark only after a batch is fully processed. If the job crashes mid-batch, that batch runs again on resume.

Solution
import math
from typing import NamedTuple
class Progress(NamedTuple):
done: int # the high-water mark: lines processed so far
revenue: float
def run(start: Progress, max_batches: int | None) -> Progress:
"""Process batches of 2,000 lines after the first start.done lines."""
done, revenue = start
remaining = islice(read_rows("data/sales.csv"), done, None)
for batch in islice(batched(remaining, 2_000), max_batches):
revenue += sum(float(r["revenue"]) for r in batch)
done += len(batch) # the high-water mark moves after the whole batch
return Progress(done, revenue)
mark = run(Progress(0, 0.0), max_batches=3)
print(f"crash after line {mark.done:,}; revenue so far {mark.revenue:,.2f}")
final = run(mark, max_batches=None)
print(f"resumed and finished: {final.done:,} lines, revenue {final.revenue:,.2f}")
full = sum(float(r["revenue"]) for r in read_rows("data/sales.csv"))
assert final.done == 20228
assert math.isclose(final.revenue, full)
Output
crash after line 6,000; revenue so far 1,076,852.90
resumed and finished: 20,228 lines, revenue 3,596,523.83

How it works:

  1. The first run takes 3 batches of 2,000 lines and stops: line 6,000 is the high-water mark.
  2. The second run starts from the returned Progress, skips the first 6,000 lines with islice(rows, 6000, None) and processes the rest. A NamedTuple keeps the line count an int and the revenue a float.
  3. The mark moves only after a whole batch, so a crash inside a batch would repeat that batch, never skip it.
  4. The final count equals the file’s 20,228 lines, and the revenue equals one full pass. Every line was processed exactly once.

Interpretation: skipping by position still reads the first 6,000 lines from disk; it only skips their processing. Real jobs store a key instead, such as the last loaded order_id, end each batch at a whole order, and ask the database for “rows after this key”, which reads nothing twice.

Alternative: save the mark to a JSON file (module 07) after each batch, so the resume also works after a real crash of the Python process.