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:
- Read the task and the expected output.
- Copy the setup block below and the starter code into a script (for example
exercise.py). Replace each to-do comment with your code. - Run the script from your project folder with
python exercise.py. Compare your output with the expected output. - 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 csvfrom collections import Counter, defaultdict, dequefrom collections.abc import Iterable, Iteratorfrom 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
Section titled “Warm-up”M10-W01 · Walk an iterator by hand
Section titled “M10-W01 · Walk an iterator by hand”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.
okwarnfaildonestatuses = ["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] == statusesassert fourth == "done"assert next(it, None) is None # still exhaustedokwarnfaildoneHow it works:
iter(statuses)returns alist_iteratorthat points before the first item.- Each
next(it)returns the next item and moves the position. - After
"fail", the iterator is exhausted.next(it, "done")returns the default instead of raisingStopIteration.
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")okwarnfaildoneM10-W02 · Predict the evaluation order
Section titled “M10-W02 · Predict the evaluation order”Predict the output: read the code and write down, line by line, what it prints. Then run it.
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"startloadgot rowscleangot clean rowssaveendHow it works:
g = stages()creates the generator. Nothing prints, sostartcomes first.- The first loop step runs the body to
yield "rows":loadprints, then the loop printsgot rows. - The second step resumes after the first
yield:clean, thengot clean rows. - The third step resumes again, prints
saveand reaches the end of the body. The generator raisesStopIteration, and the loop ends beforeendprints.
M10-W03 · Convert a stream of readings
Section titled “M10-W03 · Convert a stream of readings”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.
[68.4, 72.1, 66.9, 76.1]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 valuesHint 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[68.4, 72.1, 66.9, 76.1]How it works:
- The
yieldmakesto_fahrenheita generator function. Calling it returns a generator. list()callsnext()until the generator ends, and collects the four values.- 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.
M10-W04 · Sum with generator expressions
Section titled “M10-W04 · Sum with generator expressions”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.
units: 5discounted lines: 2lines = [ {"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 linesHint 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 == 5assert discounted == 2units: 5discounted lines: 2How it works:
sum(line["quantity"] for line in lines)passes a generator tosum(), which pulls one quantity at a time.sum(1 for ... if ...)adds 1 for each line that passes the filter, which counts them.- 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.
M10-W05 · Fix the empty mean
Section titled “M10-W05 · Fix the empty mean”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.
count: 4mean: 21.5raw = ["21.0", "21.9", "21.4", "21.7"]temps = map(float, raw)count = len(list(temps))mean = sum(temps) / countprint("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 oncecount = len(temps)mean = sum(temps) / countprint("count:", count)print("mean:", round(mean, 2))assert count == 4assert round(mean, 2) == 21.5count: 4mean: 21.5How it works:
- In the bug,
list(temps)exhausted themapiterator, sosum(temps)added nothing and returned 0. - The fix stores the values in a list once. A list is re-iterable, so
len()andsum()both see all four values. - 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.
M10-W06 · Take a slice of a stream
Section titled “M10-W06 · Take a slice of a stream”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.
O000074 Trail Running ShoesO000075 Air PurifierO000076 A Brief History of Mapsrows = read_rows("data/sales.csv")# TODO: islice the stream to data rows 101..103# TODO: print order_id and product of eachHint 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) == 3assert all(row["order_date"].startswith("2023-01") for row in selected)O000074 Trail Running ShoesO000075 Air PurifierO000076 A Brief History of MapsHow it works:
islice(rows, 100, 103)reads and drops the first 100 rows, then yields 3 rows and stops.- The source stops after row 103. The rest of the file is never read.
- 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”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.
['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08']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 listHint 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) == 8assert flat[3] == "S04"['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08']How it works:
- The outer loop takes one group at a time.
yield from grouphands each store id of the group to the caller before the loop moves on.- 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)))['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08']M10-W08 · Batch API calls
Section titled “M10-W08 · Batch API calls”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.
call 1: S01 S02 S03 S04 S05call 2: S06 S07 S08 S09 S10call 3: S11 S12store_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")call 1: S01 S02 S03 S04 S05call 2: S06 S07 S08 S09 S10call 3: S11 S12How it works:
batched(store_ids, 5)yields(S01, …, S05),(S06, …, S10)and the rest,(S11, S12).enumerateadds a call number, starting at 1.- 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.
M10-W09 · Choose a list or a generator
Section titled “M10-W09 · Choose a list or a generator”Choose a method and justify it: for each task, decide whether a list comprehension or a generator expression fits better. Then run your choice.
- Total revenue of
data/sales.csv. - The 12 store floor areas in square feet (1 m² = 10.764 sq ft), used three times: smallest, largest and total.
- Is any temperature in
data/sensors.csvat 42 °C or above (thefaillimit)?
total revenue: 3,596,523.83sq ft min, max, total: 14531 36598 282340any reading >= 42 °C: Truesizes_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.83assert len(sizes_sqft) == 12assert hottotal revenue: 3,596,523.83sq ft min, max, total: 14531 36598 282340any reading >= 42 °C: TrueHow it works:
- The revenue total reads each row once and keeps nothing, so a generator expression fits.
min(),max()andsum()each loop over the values. A generator would be empty aftermin(). The data has 12 items, so a list costs nothing.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”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).
['2024-01-01', '2024-01-02', '2024-01-03']days in 2024: 366from datetime import date, timedeltafrom 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 2024Hint 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, timedeltafrom 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 == 366assert next(year) == date(2024, 1, 4) # the first object kept its position['2024-01-01', '2024-01-02', '2024-01-03']days in 2024: 366How it works:
__init__stores the position (current) and the stop date.__iter__returns the object itself, which makes it an iterator.__next__returns one date per call and raisesStopIterationafterend.islice(year, 3)took three dates. The last assert shows thatyearremembers 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))))731The 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”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.
days: 7weekend: ['2024-07-14', '2024-07-20']from datetime import date, timedeltafrom 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 == 7assert weekend == ["2024-07-14", "2024-07-20"]assert iter(week) is not iter(week) # a fresh iterator each timedays: 7weekend: ['2024-07-14', '2024-07-20']How it works:
- The object now stores only
startandend, which never change. __iter__containsyield, so each call returns a new generator that starts atstart.sum()and the list comprehension each calliter(week)and get their own generator, so both see 7 days.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.
M10-C03 · Stream one store’s sales
Section titled “M10-C03 · Stream one store’s sales”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.
S12: 868 lines, revenue 152,673.29, first sale 2023-06-15s12 = ... # TODO: generator expression of S12 rowslines = 0revenue = 0.0first_date = None# TODO: one loop that updates the three results# TODO: print the reportHint 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 = 0revenue = 0.0first_date = Nonefor 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 == 868assert first_date == "2023-06-15"assert abs(revenue - 152673.29) < 0.01S12: 868 lines, revenue 152,673.29, first sale 2023-06-15How it works:
- The generator expression passes on only S12 rows, one at a time.
- One loop updates three results, so the file is read once.
- Because
data/sales.csvis sorted by date, the first S12 row is its opening day: 2023-06-15, as indata/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.
M10-C04 · Find the bulk orders
Section titled “M10-C04 · Find the bulk orders”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).
bulk lines: 29O003982 25 x Slim Fit JeansO008005 25 x Weeknight Kitchen CookbookO010887 25 x Slim Fit Jeansdef 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 3Hint 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) == 29assert all(q >= 10 for _, _, q in bulk)bulk lines: 29O003982 25 x Slim Fit JeansO008005 25 x Weeknight Kitchen CookbookO010887 25 x Slim Fit JeansHow it works:
- The generator streams the 20,228 rows and passes on only the 29 bulk lines.
- Storing the 29 results in a list is cheap, and it allows
len()and sorting. sorted()withreverse=Trueputs 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.
M10-C05 · Average revenue per chunk
Section titled “M10-C05 · Average revenue per chunk”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?
chunk 1: from 2023-01-01, 5000 lines, mean 179.85chunk 2: from 2023-08-19, 5000 lines, mean 181.35chunk 3: from 2024-02-14, 5000 lines, mean 167.31chunk 4: from 2024-08-18, 5000 lines, mean 181.24chunk 5: from 2024-12-27, 228 lines, mean 209.56for 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) == 5chunk 1: from 2023-01-01, 5000 lines, mean 179.85chunk 2: from 2023-08-19, 5000 lines, mean 181.35chunk 3: from 2024-02-14, 5000 lines, mean 167.31chunk 4: from 2024-08-18, 5000 lines, mean 181.24chunk 5: from 2024-12-27, 228 lines, mean 209.56How it works:
batchedgroups the stream into tuples of 5,000 rows. The fifth chunk holds the last 228.- Inside one chunk, indexing and
len()work, because a chunk is a tuple. - 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.
M10-C06 · Fix the endless chunker
Section titled “M10-C06 · Fix the endless chunker”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.
5 O0000015 O0000065 O0000115 O0000163 O000021def 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)) == 55 O0000015 O0000065 O0000115 O0000163 O000021How it works:
- A list is iterable but not an iterator. Each
islice(order_ids, 5)callediter()on the list again and started from the top. it = iter(iterable)creates one iterator. Everyislice(it, 5)continues where the last one stopped.- On a stream (an iterator),
iter()returns the same object, so the function works for both. - 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.
M10-C07 · Clean the humidity column
Section titled “M10-C07 · Clean the humidity column”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.
S1: mean 55.0 %, skipped 11S2: mean 55.0 %, skipped 8S3: mean 51.3 %, skipped 5S4: mean 55.2 %, skipped 5def 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 skippedHint 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] += 1for 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() == 29assert counts.total() + skipped.total() == 8064S1: mean 55.0 %, skipped 11S2: mean 55.0 %, skipped 8S3: mean 51.3 %, skipped 5S4: mean 55.2 %, skipped 5How it works:
if not row["humidity_pct"]catches the empty string. The generator counts the gap and moves on withcontinue.- The sink keeps a running sum and count per sensor, so memory holds 4 sums and 4 counts.
skippedis complete only after the loop, because the generator fills it while it runs.- 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.
M10-C08 · Track the drift of sensor S3
Section titled “M10-C08 · Track the drift of sensor S3”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.
2024-05-01 21.292024-05-02 21.602024-05-13 25.342024-05-14 25.8514 days, drift +0.35 °C per dayfrom itertools import groupbyfrom statistics import fmean
s3 = ... # TODO: generator of (date, temperature) for S3 rows with a temperaturedaily = ... # TODO: list of (date, mean) with groupby# TODO: print the first two and last two days, and the drift per dayHint 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 groupbyfrom 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) == 14assert 0.3 < drift < 0.42024-05-01 21.292024-05-02 21.602024-05-13 25.342024-05-14 25.8514 days, drift +0.35 °C per dayHow it works:
- The generator expression filters to S3, skips blanks and keeps only the date and the temperature.
groupbygroups consecutive pairs with the same date. It works because the file is sorted by time.- Inside the comprehension, each group is consumed by
fmeanbeforegroupbymoves on. - 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.
M10-C09 · Rolling vibration of sensor S4
Section titled “M10-C09 · Rolling vibration of sensor S4”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.
first rolling mean >= 4.5: 2024-05-01T08:00:00highest rolling mean: 10.53 mm/sfrom statistics import fmean
window: deque[float] = deque(maxlen=6)first_warn = Nonehighest = 0.0# TODO: loop over S4 rows with a vibration value; update the window and resultsHint 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 = Nonehighest = 0.0s4 = ( 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 Noneassert first_warn == "2024-05-01T08:00:00"first rolling mean >= 4.5: 2024-05-01T08:00:00highest rolling mean: 10.53 mm/sHow it works:
- The generator expression keeps only S4 rows with a vibration value.
- The deque holds the last 6 values;
fmeanaverages them. - The first hour-long mean at the
warnlevel 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”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.
online 339,645.97store 528,537.43def 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)online 339,645.97store 528,537.43How it works:
- Source.
read_rows()streams dicts instead of loading every line withreadlines(). - Names, not positions.
row["revenue"]replacesx[12]. The code no longer breaks when a column moves, and it is correct even if a field contains a quoted comma, whichsplit(",")would cut in two. - One pass. The eager script scanned the list twice, once per channel. The
defaultdictsink fills both totals in one loop, and it would handle a third channel with no new code. - 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.
M10-C11 · Fix the groupby report
Section titled “M10-C11 · Fix the groupby report”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.
groupby groups: 13493stores: 12S01 2220S02 1563S03 1183from 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 12Hint 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) == 12assert per_store["S01"] == 2220groupby groups: 13493stores: 12S01 2220S02 1563S03 1183How it works:
- The file is sorted by date, not by store. Consecutive lines come from different stores, so the key changes almost every line and
groupbymakes almost one group per line. - A
Counteradds 1 per store whatever the order. It holds 12 counts. - 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.
M10-C12 · Predict the tee output
Section titled “M10-C12 · Predict the tee output”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.
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_leftassert rest_right[:2] == [20.21, 20.22]20.21 20.2220.16[20.21, 20.22, 19.93, 19.9][19.93, 19.9]How it works:
lefttook 20.21 and 20.22.teeread them fromreadingsand stored them forright.next(readings)took 20.16 straight from the source.teenever saw it, so both copies lose it.rightfirst gets the two stored values, then 19.93 and 19.9 from the source.leftgets only 19.93 and 19.9.- 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”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.
Beauty 83Sports 82Electronics 76Clothing 74Books 52Home 42total 409from itertools import chainfrom pathlib import Path
paths = sorted(Path("data/reports").glob("2024-*.csv"))all_rows = ... # TODO: one stream over every fileunits: Counter[str] = Counter()# TODO: add the quantity of each row to its category; print the rankingHint 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 chainfrom 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) == 6Beauty 83Sports 82Electronics 76Clothing 74Books 52Home 42total 409How it works:
chain.from_iterabletakes the generator of sixread_rows()streams and yields their rows one after another. Each file opens only when the chain reaches it.DictReadermaps each value to its column name, so April’s different column order changes nothing.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
Section titled “Challenge”M10-X01 · Streaming ETL into SQLite
Section titled “M10-X01 · Streaming ETL into SQLite”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.
batches: 6Electronics 1046 427,426.51Home 825 181,857.19Sports 851 143,396.72Clothing 1011 79,829.48Beauty 767 37,994.15Books 650 26,109.36total 896,613.41import 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 totalHint 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 mathimport 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 == 6batches: 6Electronics 1046 427,426.51Home 825 181,857.19Sports 851 143,396.72Clothing 1011 79,829.48Beauty 767 37,994.15Books 650 26,109.36total 896,613.41How it works:
- Extract returns the lazy
read_rows()stream. Nothing is read yet. - Transform filters and reshapes one row at a time into small tuples.
- Load pulls the stream in batches of 1,000 and inserts each with one
executemanycall. The 5,150 online lines of 2024 need 6 calls. - 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”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?
{'S1': 7, 'S2': 10, 'S3': 12, 'S4': 10} total 392024-05-01T08:00:00 S4 12.92 mm/s vs median 3.052024-05-02T00:20:00 S1 7.53 mm/s vs median 2.212024-05-02T10:10:00 S1 7.53 mm/s vs median 1.86from 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 spikesHint 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{'S1': 7, 'S2': 10, 'S3': 12, 'S4': 10} total 392024-05-01T08:00:00 S4 12.92 mm/s vs median 3.052024-05-02T00:20:00 S1 7.53 mm/s vs median 2.212024-05-02T10:10:00 S1 7.53 mm/s vs median 1.86How it works:
- One deque per sensor holds its last 6 normal readings. The
defaultdictcreates each on first use. - The median of 6 values is the mean of the middle two after sorting. One extreme value in the window barely moves it.
- A spike is yielded and kept out of the window, so the baseline stays clean.
- 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”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).
skipped traceback lines: 8levels: {'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=2import 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 requestsHint 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] == 500assert levels["INFO"] == 447assert len(slowest) == 3skipped traceback lines: 8levels: {'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=2How it works:
read_linesstreams the file.skip_tracebackspasses on lines that start with a digit and counts the rest in a one-item list, which the generator can change in place.parsesplits each line at most 4 times, so the message keeps its spaces.count_levelsis a pass-through stage: it counts each record and yields it unchanged. This gives a side result without a second pass.api_requestunpacks the six fields of a request message.heapq.nlargestconsumes the stream of API tuples and keeps only the top 3. Tuples compare by their first item, the duration.- Every sink result is complete after
nlargesthas 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”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?
S1: 14 problem readings, longest streak 1 from 2024-05-02T00:20:00S2: 22 problem readings, longest streak 1 from 2024-05-01T00:40:00S3: 22 problem readings, longest streak 1 from 2024-05-01T10:40:00S4: 419 problem readings, longest streak 272 from 2024-05-13T02:40:00from 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 sensorHint 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"S1: 14 problem readings, longest streak 1 from 2024-05-02T00:20:00S2: 22 problem readings, longest streak 1 from 2024-05-01T00:40:00S3: 22 problem readings, longest streak 1 from 2024-05-01T10:40:00S4: 419 problem readings, longest streak 272 from 2024-05-13T02:40:00How it works:
sensor_statusesstreams one sensor’s(timestamp, status)pairs in time order.groupby(..., key=lambda s: s[1] != "ok")splits the stream into alternating runs of normal and problem readings.problem_streakshandles each problem run:next(group)takes the first reading (its start time), andsum(1 for _ in group)counts the rest. Each group is used beforegroupbymoves on.max(..., key=...)keeps the longest run. No stage stores more than one reading.- The cost: two passes per sensor, so the loop reads
data/sensors.csv8 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”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.
O001531 2023-04-24 lines=1 5,196.00O014369 2024-12-17 lines=2 4,975.98O011849 2024-09-25 lines=1 4,596.00O006934 2024-01-14 lines=1 4,596.00O006473 2023-12-23 lines=2 4,526.18orders: 14877import heapqfrom 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.nlargestHint 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 heapqfrom 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 == 14877assert top[0][1] == "O001531"O001531 2023-04-24 lines=1 5,196.00O014369 2024-12-17 lines=2 4,975.98O011849 2024-09-25 lines=1 4,596.00O006934 2024-01-14 lines=1 4,596.00O006473 2023-12-23 lines=2 4,526.18orders: 14877How it works:
groupbyonorder_idturns the line stream into an order stream, one order at a time.- Each order is at most 3 lines, so
list(group)is safe. The stage yields a tuple whose first item is the total. 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.- The order count matches the data dictionary (14,877 orders), which proves that
groupbysaw 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”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.
crash after line 6,000; revenue so far 1,076,852.90resumed and finished: 20,228 lines, revenue 3,596,523.83from 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 stateHint 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 == 20228assert math.isclose(final.revenue, full)crash after line 6,000; revenue so far 1,076,852.90resumed and finished: 20,228 lines, revenue 3,596,523.83How it works:
- The first run takes 3 batches of 2,000 lines and stops: line 6,000 is the high-water mark.
- The second run starts from the returned
Progress, skips the first 6,000 lines withislice(rows, 6000, None)and processes the rest. ANamedTuplekeeps the line count anintand the revenue afloat. - The mark moves only after a whole batch, so a crash inside a batch would repeat that batch, never skip it.
- 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.