Skip to content

13. Pythonic code — Exercises

These exercises practice every idea of the Pythonic code lesson. They use the course datasets: sensor readings, monthly sales extracts, customer records and the raw sales file.

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block and the starter code into a script and replace each to-do comment with your code.
  3. Run the script and compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Many tasks start from working but messy code. For a refactor, keep the output identical: run the old code first and keep its output to compare. Run ruff check on your solution too.

Every solution on this page starts with these imports. Put them at the top of your script.

import csv
import json
import math
from collections import Counter, defaultdict
from decimal import ROUND_HALF_UP, Decimal
from pathlib import Path
from typing import Any

M13-W01 · Number the products with enumerate

Section titled “M13-W01 · Number the products with enumerate”
Warm-up

Refactor: the loop below prints a numbered list of the first five products of data/products.csv. Rewrite it with enumerate() and an f-string. Build the lines in a list first, so you can check them.

Expected output
1) Wireless Earbuds
2) Noise-Cancelling Headphones
3) 55-inch 4K Smart TV
4) 14-inch Ultrabook Laptop
5) Smartwatch Series 5
Starter
products = [
"Wireless Earbuds",
"Noise-Cancelling Headphones",
"55-inch 4K Smart TV",
"14-inch Ultrabook Laptop",
"Smartwatch Series 5",
]
for i in range(len(products)):
print(str(i + 1) + ") " + products[i])
# TODO: build `lines` with enumerate(..., start=1) and an f-string, then print them
Hint 1

enumerate(products, start=1) gives the pairs (1, "Wireless Earbuds"), (2, "Noise-Cancelling Headphones") and so on.

Hint 2

A list comprehension builds the lines: [f"{number}) {name}" for number, name in ...].

Solution
products = [
"Wireless Earbuds",
"Noise-Cancelling Headphones",
"55-inch 4K Smart TV",
"14-inch Ultrabook Laptop",
"Smartwatch Series 5",
]
lines = [f"{number}) {name}" for number, name in enumerate(products, start=1)]
for line in lines:
print(line)
assert lines[0] == "1) Wireless Earbuds"
assert lines[-1] == "5) Smartwatch Series 5"
Output
1) Wireless Earbuds
2) Noise-Cancelling Headphones
3) 55-inch 4K Smart TV
4) 14-inch Ultrabook Laptop
5) Smartwatch Series 5

How it works:

  1. enumerate(products, start=1) produces a count and an item for each product. The count starts at 1, so no i + 1 is needed.
  2. The comprehension unpacks each pair into number and name.
  3. The f-string replaces str() and the four + signs.

Alternative: print in one call with print("\n".join(lines)). It writes the same five lines.

M13-W02 · Pair sensor ids and readings with zip

Section titled “M13-W02 · Pair sensor ids and readings with zip”
Warm-up

The first timestamp of data/sensors.csv has these temperatures. Build a dict latest that maps each sensor id to its temperature with zip(..., strict=True) and dict(). Then print the dict and the hottest sensor.

Expected output
{'S1': 20.21, 'S2': 22.3, 'S3': 19.4, 'S4': 24.52}
Hottest: S4 (24.52 C)
Starter
sensor_ids = ["S1", "S2", "S3", "S4"]
temps = [20.21, 22.3, 19.4, 24.52]
# TODO: latest = a dict built from zip(..., strict=True)
# TODO: find the hottest sensor with max() and a key function
Hint 1

dict() accepts an iterable of (key, value) pairs, and zip() produces exactly that.

Hint 2

max(latest, key=latest.get) returns the key with the largest value.

Solution
sensor_ids = ["S1", "S2", "S3", "S4"]
temps = [20.21, 22.3, 19.4, 24.52]
latest = dict(zip(sensor_ids, temps, strict=True))
hottest = max(latest, key=latest.get)
print(latest)
print(f"Hottest: {hottest} ({latest[hottest]} C)")
assert hottest == "S4"
assert len(latest) == 4
Output
{'S1': 20.21, 'S2': 22.3, 'S3': 19.4, 'S4': 24.52}
Hottest: S4 (24.52 C)

How it works:

  1. zip() pairs the two lists item by item. strict=True raises a ValueError if one list is shorter, so a lost reading cannot pass unnoticed.
  2. dict() turns the pairs into a dict.
  3. Looping over a dict gives its keys. key=latest.get makes max() compare the values.

Alternative: a dict comprehension, {s: t for s, t in zip(sensor_ids, temps, strict=True)}, does the same. dict(zip(...)) is shorter when you do not change the pairs.

Warm-up

Count the lines per category in data/reports/2024-01.csv with dict.get(). Print the categories from the most lines to the fewest, one per line.

Expected output
Electronics: 15
Sports: 11
Clothing: 8
Books: 5
Beauty: 5
Home: 4
Starter
with Path("data/reports/2024-01.csv").open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
counts: dict[str, int] = {}
# TODO: count rows per category with counts.get(category, 0) + 1
# TODO: print "Category: n" from the largest count to the smallest
Hint 1

Inside the loop: counts[row["category"]] = counts.get(row["category"], 0) + 1.

Hint 2

Sort the pairs by their count: sorted(counts.items(), key=lambda item: item[1], reverse=True).

Solution
with Path("data/reports/2024-01.csv").open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
counts: dict[str, int] = {}
for row in rows:
counts[row["category"]] = counts.get(row["category"], 0) + 1
for category, count in sorted(counts.items(), key=lambda item: item[1], reverse=True):
print(f"{category}: {count}")
assert sum(counts.values()) == len(rows) == 48
Output
Electronics: 15
Sports: 11
Clothing: 8
Books: 5
Beauty: 5
Home: 4

How it works:

  1. counts.get(category, 0) returns 0 for a category that the dict has not seen yet, so the first line of each category starts the count at 1.
  2. sorted() with reverse=True puts the largest count first. sorted() is stable, so categories with the same count keep their first-seen order.
  3. The assert checks that every row was counted exactly once.

Alternative: Counter does the counting and the sorting.

with Path("data/reports/2024-01.csv").open(newline="", encoding="utf-8") as f:
counts = Counter(row["category"] for row in csv.DictReader(f))
for category, count in counts.most_common():
print(f"{category}: {count}")
Output
Electronics: 15
Sports: 11
Clothing: 8
Books: 5
Beauty: 5
Home: 4

M13-W04 · Predict the output: any, all and empty data

Section titled “M13-W04 · Predict the output: any, all and empty data”
Warm-up

Predict the output: write down what each line prints. Then run the code and compare.

Acceptance criteria:

  • Write your prediction for every line before you run the code.
  • Run the code. Your prediction matches the Output in the solution, line by line.
  • You can explain the result of the two lines that use empty.
Starter
quantities = [1, 2, 25, 1]
empty: list[int] = []
print(any(q > 10 for q in quantities))
print(all(q >= 1 for q in quantities))
print(sum(q > 1 for q in quantities))
print(any(q > 10 for q in empty))
print(all(q >= 1 for q in empty))
# TODO: write your prediction for each line before you run it
Hint 1

True counts as 1 in a sum. any() needs one truthy value; all() needs no falsy value.

Hint 2

An empty iterable has no truthy value, and it also has no falsy value.

Solution
quantities = [1, 2, 25, 1]
empty: list[int] = []
print(any(q > 10 for q in quantities))
print(all(q >= 1 for q in quantities))
print(sum(q > 1 for q in quantities))
print(any(q > 10 for q in empty))
print(all(q >= 1 for q in empty))
assert sum(q > 1 for q in quantities) == 2
assert all(q >= 1 for q in empty) and not any(q > 10 for q in empty)
Output
True
True
2
False
True

How it works:

  1. 25 > 10, so any() is True. Every quantity is at least 1, so all() is True.
  2. q > 1 is True for 2 and 25, so the sum is 2.
  3. any() of nothing is False: no value is truthy.
  4. all() of nothing is True: no value breaks the rule. This is vacuous truth. A quality gate built on all() alone passes on an empty file.

Alternative: to make an empty input fail the gate, write bool(empty) and all(q >= 1 for q in empty). It is False for an empty list.

M13-W05 · Sum with a generator expression

Section titled “M13-W05 · Sum with a generator expression”
Warm-up

From data/reports/2024-02.csv, compute three numbers with sum() and a generator expression: the revenue of the Beauty lines, the units of the Beauty lines and the number of lines (any category) with a quantity above 1. Do not build intermediate lists.

Expected output
Beauty: 25 units, revenue 702.29 USD
Lines with more than 1 unit: 14
Starter
with Path("data/reports/2024-02.csv").open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
# TODO: beauty_revenue, beauty_units, multi_unit_lines with sum(... for row in rows ...)
# TODO: print the three values
Hint 1

sum(float(row["revenue"]) for row in rows if row["category"] == "Beauty") adds the revenue of the Beauty lines.

Hint 2

To count, sum booleans: sum(int(row["quantity"]) > 1 for row in rows).

Solution
with Path("data/reports/2024-02.csv").open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
beauty_revenue = sum(
float(row["revenue"]) for row in rows if row["category"] == "Beauty"
)
beauty_units = sum(int(row["quantity"]) for row in rows if row["category"] == "Beauty")
multi_unit_lines = sum(int(row["quantity"]) > 1 for row in rows)
print(f"Beauty: {beauty_units} units, revenue {beauty_revenue:.2f} USD")
print(f"Lines with more than 1 unit: {multi_unit_lines}")
assert sum(row["category"] == "Beauty" for row in rows) == 14
assert beauty_units >= 14
Output
Beauty: 25 units, revenue 702.29 USD
Lines with more than 1 unit: 14

How it works:

  1. Each sum() filters the rows with its own if clause, so no list of Beauty rows is built.
  2. Each sum() consumes a generator expression, so no list of numbers is built.
  3. int(row["quantity"]) > 1 is a boolean, and the sum counts the True values.

Alternative: filter once into a list, beauty = [row for row in rows if row["category"] == "Beauty"], and sum over beauty twice. The condition is written once, at the cost of an extra list in memory.

Warm-up

The first line of data/logs/app.log is an API request. Split it on whitespace and unpack the parts into named variables, with no index such as parts[2]. Then print the summary line below. Use *rest for the fields you do not need at the end, or _ for single fields you skip.

Expected output
INFO GET /api/v1/reports/2024-04 -> 200 in 87ms
Starter
line = (
"2024-05-01 08:04:01,354 INFO [api] 10.0.3.17 GET /api/v1/reports/2024-04 "
"200 87ms user=priya.nair@example.com"
)
# TODO: unpack line.split() into date, time, level, component, ip, method, path, ...
# TODO: print "INFO GET /api/v1/reports/2024-04 -> 200 in 87ms"
Hint 1

line.split() gives 10 parts. Count the names on the left side.

Hint 2

Put one name per field on the left side, in order. Use *rest for the trailing fields you do not need, and check that the count of names matches.

Solution
line = (
"2024-05-01 08:04:01,354 INFO [api] 10.0.3.17 GET /api/v1/reports/2024-04 "
"200 87ms user=priya.nair@example.com"
)
date, time, level, component, ip, method, path, status, duration, *rest = line.split()
print(f"{level} {method} {path} -> {status} in {duration}")
assert component == "[api]"
assert rest == ["user=priya.nair@example.com"]
Output
INFO GET /api/v1/reports/2024-04 -> 200 in 87ms

How it works:

  1. The two string literals in parentheses join into one string. This keeps the line under 88 characters.
  2. split() with no argument splits on any run of whitespace.
  3. Nine names take the first nine parts. *rest collects whatever is left, here one item. If a line had fewer than nine parts, unpacking would raise a ValueError at once.

Alternative: module 09 parses these lines with a regular expression. That is more robust when a field can contain spaces.

M13-W07 · Fix the bug: identity instead of equality

Section titled “M13-W07 · Fix the bug: identity instead of equality”
Warm-up

Fix the bug: the code counts warn rows in two lines of data/sensors.csv, but it prints Warnings: 0. Line 19 of the file is a warning. Fix the comparison.

Expected output
Warnings: 1
Starter
WARN = "warn"
lines = [
"2024-05-01T00:40:00,S2,38.03,59.0,2.39,warn",
"2024-05-01T00:40:00,S3,19.11,55.5,2.23,ok",
]
warnings = 0
for line in lines:
*_, status = line.split(",")
if status is WARN: # TODO: fix this comparison
warnings += 1
print(f"Warnings: {warnings}")
Hint 1

is checks if two names refer to the same object. Is the string from split() the same object as the constant WARN?

Solution
WARN = "warn"
lines = [
"2024-05-01T00:40:00,S2,38.03,59.0,2.39,warn",
"2024-05-01T00:40:00,S3,19.11,55.5,2.23,ok",
]
warnings = 0
for line in lines:
*_, status = line.split(",")
if status == WARN:
warnings += 1
print(f"Warnings: {warnings}")
assert warnings == 1
Output
Warnings: 1

How it works:

  1. split(",") creates new string objects. The last part is equal to "warn", but it is not the same object as WARN, so status is WARN is False.
  2. == compares the values, which is what the task needs.
  3. *_, status keeps only the last field. _ collects the fields before it.

Alternative: sum(line.split(",")[-1] == WARN for line in lines) counts in one expression.

M13-W08 · Apply PEP 8 to a small function

Section titled “M13-W08 · Apply PEP 8 to a small function”
Warm-up

Refactor: rewrite the function below in Pythonic, PEP 8 style. Use a snake_case name, a clear parameter name, type hints, a truthiness test instead of == None and len() == 0, and sum() instead of the index loop. Test it on six readings from data/readings.txt and on an empty list.

Expected output
20.58
None
Starter
def CalcMean(L):
if L == None or len(L) == 0:
return None
Total = 0
for i in range(len(L)):
Total = Total + L[i]
return Total / len(L)
# TODO: write mean(values) in PEP 8 style
readings = [19.5, 20.7, 20.1, 21.2, 21.2, 20.8]
Hint 1

if not values: is True for None and for an empty list.

Hint 2

The return type is float | None, because an empty input has no mean.

Solution
def mean(values: list[float] | None) -> float | None:
"""Return the arithmetic mean, or None when there are no values."""
if not values:
return None
return sum(values) / len(values)
readings = [19.5, 20.7, 20.1, 21.2, 21.2, 20.8]
print(f"{mean(readings):.2f}")
print(mean([]))
assert math.isclose(mean(readings), 123.5 / 6)
assert mean([]) is None and mean(None) is None
Output
20.58
None

How it works:

  1. mean is snake_case and values says what the parameter holds. L is a one-letter name that says nothing about its content, and an uppercase name for a variable breaks the snake_case rule. (PEP 8 forbids l, O and I as names, because in many fonts they look like 1 and 0.)
  2. if not values: covers None and [] in one test.
  3. sum(values) replaces the index loop and the accumulator.
  4. The assert uses math.isclose(), because the mean is a computed float.

Alternative: statistics.fmean(values) (module 09) computes a float mean, but it raises StatisticsError on an empty list instead of returning None.

M13-C01 · Group sensor vibration with setdefault

Section titled “M13-C01 · Group sensor vibration with setdefault”
Core

Read the first 40 data rows of data/sensors.csv (10 timestamps × 4 sensors). Group the vibration values by sensor with setdefault(), skipping blank cells. Print the count, minimum and maximum per sensor in sensor order.

Expected output
S1: 10 values, min 1.7, max 2.67
S2: 10 values, min 2.15, max 3.39
S3: 10 values, min 1.65, max 2.5
S4: 10 values, min 2.17, max 3.83
Starter
with Path("data/sensors.csv").open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))[:40]
vibration: dict[str, list[float]] = {}
# TODO: group float(row["vibration_mm_s"]) by row["sensor_id"], skip blanks
# TODO: print "S1: n values, min ..., max ..." in sorted order
Hint 1

vibration.setdefault(sensor_id, []).append(value) creates the list on first use.

Hint 2

for sensor_id, values in sorted(vibration.items()): visits the sensors in order and unpacks each pair.

Solution
with Path("data/sensors.csv").open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))[:40]
vibration: dict[str, list[float]] = {}
for row in rows:
if row["vibration_mm_s"]:
vibration.setdefault(row["sensor_id"], []).append(float(row["vibration_mm_s"]))
for sensor_id, values in sorted(vibration.items()):
print(f"{sensor_id}: {len(values)} values, min {min(values)}, max {max(values)}")
assert sum(len(v) for v in vibration.values()) == 40
Output
S1: 10 values, min 1.7, max 2.67
S2: 10 values, min 2.15, max 3.39
S3: 10 values, min 1.65, max 2.5
S4: 10 values, min 2.17, max 3.83

How it works:

  1. list(...)[:40] reads the file and keeps the first 40 rows. The file is small, so reading it all is fine.
  2. A blank cell is the empty string, which is falsy, so if row["vibration_mm_s"]: skips it. These 40 rows have no blanks, as the assert confirms.
  3. setdefault() returns the list for the sensor, creating it the first time, and append() adds the value.

Alternative: defaultdict(list) removes the setdefault() call: vibration = defaultdict(list) and then vibration[row["sensor_id"]].append(...). For a file too big to read at once, itertools.islice(csv.DictReader(f), 40) reads only the first 40 rows.

M13-C02 · Fix the bug: a mutable default in a quality log

Section titled “M13-C02 · Fix the bug: a mutable default in a quality log”
Core

Fix the bug: check_quantity() should return the problems of one order line. The second call is for a valid line, but it returns the problem of the first line. Two of the real bad lines of data/sales_raw.csv are below. Fix the function, keep its optional problems parameter (a caller may pass a list to collect into) and add type hints.

Expected output
['O002118: quantity 999']
[]
['O002118: quantity 999', 'O007568: quantity -3']
Starter
def check_quantity(order_id, quantity, problems=[]):
if not 1 <= quantity <= 50:
problems.append(f"{order_id}: quantity {quantity}")
return problems
print(check_quantity("O002118", 999))
print(check_quantity("O000004", 1)) # a valid line: expected []
# TODO: fix the default, then show that a caller-supplied list still collects
Hint 1

The default list is created once, when Python runs def. Every call without a problems argument shares it.

Hint 2

Default to None. Inside the function: if problems is None: problems = [].

Solution
MAX_QUANTITY = 50
def check_quantity(
order_id: str, quantity: int, problems: list[str] | None = None
) -> list[str]:
"""Return the quantity problems of one line, added to `problems` if given."""
if problems is None:
problems = []
if not 1 <= quantity <= MAX_QUANTITY:
problems.append(f"{order_id}: quantity {quantity}")
return problems
print(check_quantity("O002118", 999))
print(check_quantity("O000004", 1))
collected: list[str] = []
for order_id, quantity in [("O002118", 999), ("O007568", -3), ("O000004", 1)]:
check_quantity(order_id, quantity, collected)
print(collected)
assert check_quantity("O000004", 1) == []
assert len(collected) == 2
Output
['O002118: quantity 999']
[]
['O002118: quantity 999', 'O007568: quantity -3']

How it works:

  1. None is immutable, so a None default is safe. The function creates a new list on each call that does not pass one.
  2. A caller who passes collected gets the problems of several lines in one list. That is the job the parameter was for.
  3. The constant MAX_QUANTITY replaces the magic number 50. It matches thresholds.max_quantity in data/config.json.

Alternative: drop the parameter and return only this line’s problems. The caller then writes collected.extend(check_quantity(...)). A function without a shared accumulator is easier to test.

M13-C03 · Fix the bug: late-binding min-max scalers

Section titled “M13-C03 · Fix the bug: late-binding min-max scalers”
Core

Fix the bug: min-max scaling maps a value to the range 0 to 1 with (x − min) / (max − min) (module 05). The code builds one scaler per column of data/customers.csv, but every scaler uses the range of the last column. Scale customer C00001 (tenure 72, monthly charges 84.69, 17 logins) correctly. Use a function factory.

Expected output
tenure_months: 1.000
monthly_charges: 0.492
logins_last_30d: 0.283
Starter
ranges = {
"tenure_months": (0, 72),
"monthly_charges": (28.05, 143.24),
"logins_last_30d": (0, 60),
}
scalers = {
column: lambda x: (x - low) / (high - low)
for column, (low, high) in ranges.items()
}
customer = {"tenure_months": 72, "monthly_charges": 84.69, "logins_last_30d": 17}
for column, value in customer.items():
print(f"{column}: {scalers[column](value):.3f}") # tenure prints 1.200
# TODO: write make_scaler(low, high) and rebuild scalers with it
Hint 1

The lambdas look up low and high when they run, not when they are created. By then, the comprehension has finished with the last column.

Hint 2

def make_scaler(low, high): defines an inner function and returns it. Each call has its own low and high.

Solution
from collections.abc import Callable
ranges = {
"tenure_months": (0, 72),
"monthly_charges": (28.05, 143.24),
"logins_last_30d": (0, 60),
}
def make_scaler(low: float, high: float) -> Callable[[float], float]:
"""Return a function that maps low..high to 0..1."""
def scale(x: float) -> float:
return (x - low) / (high - low)
return scale
scalers = {column: make_scaler(low, high) for column, (low, high) in ranges.items()}
customer = {"tenure_months": 72, "monthly_charges": 84.69, "logins_last_30d": 17}
scaled = {column: scalers[column](value) for column, value in customer.items()}
for column, value in scaled.items():
print(f"{column}: {value:.3f}")
assert scaled["tenure_months"] == 1.0
assert all(0 <= v <= 1 for v in scaled.values())
Output
tenure_months: 1.000
monthly_charges: 0.492
logins_last_30d: 0.283

How it works:

  1. In the starter, all three lambdas share the comprehension’s low and high. When they run, these hold (0, 60), so the tenure 72 becomes 72 / 60 = 1.2.
  2. Each call of make_scaler() creates a new scope with its own low and high, and scale remembers that scope.
  3. The asserts check two properties of min-max scaling: the maximum maps to 1, and every value of the range maps into 0..1.

Alternative: bind early with defaults, lambda x, low=low, high=high: (x - low) / (high - low). It works, but a caller could pass low= by mistake. Module 33 uses scikit-learn’s MinMaxScaler, which stores the ranges as attributes.

M13-C04 · Fix the bug: dropping spikes while iterating

Section titled “M13-C04 · Fix the bug: dropping spikes while iterating”
Core

Fix the bug: the loop should remove every temperature above 30 °C from a burst of S2 readings, but one spike survives. (The list adds a second spike next to the real 38.03 to show the bug.) Fix it so that you get both the kept readings and the removed spikes, without changing a list while you loop over it.

Expected output
kept: [22.3, 22.41, 22.5, 22.38]
spikes: [38.03, 37.2]
Starter
temps = [22.3, 22.41, 38.03, 37.2, 22.5, 22.38]
for t in temps:
if t > 30:
temps.remove(t)
print(temps) # 37.2 is still there
# TODO: build `kept` and `spikes` with two comprehensions instead
Hint 1

After remove(38.03), the value 37.2 moves into the position the loop just checked.

Hint 2

kept = [t for t in temps if t <= 30] and the opposite condition for spikes.

Solution
SPIKE_C = 30.0
temps = [22.3, 22.41, 38.03, 37.2, 22.5, 22.38]
kept = [t for t in temps if t <= SPIKE_C]
spikes = [t for t in temps if t > SPIKE_C]
print("kept:", kept)
print("spikes:", spikes)
assert len(kept) + len(spikes) == len(temps)
assert max(kept) <= SPIKE_C
Output
kept: [22.3, 22.41, 22.5, 22.38]
spikes: [38.03, 37.2]

How it works:

  1. The original list stays unchanged, so you can still compare before and after.
  2. The two comprehensions use opposite conditions, so every reading lands in exactly one list. The first assert checks it.
  3. No item is skipped, because nothing moves while a loop runs.

Alternative: one loop that appends to two lists does a single pass:

kept, spikes = [], []
for t in [22.3, 22.41, 38.03, 37.2, 22.5, 22.38]:
(spikes if t > 30 else kept).append(t)
print(kept, spikes)
Output
[22.3, 22.41, 22.5, 22.38] [38.03, 37.2]
Core

Read data/readings.txt. Convert each line with float() in EAFP style. Collect the valid values and the bad lines as (line number, text) pairs, with the line numbers that an editor shows. Print the count and mean of the valid values, then the bad lines.

Expected output
40 valid readings, mean 21.06
Bad lines: [(12, 'error'), (24, ''), (35, 'n/a')]
Starter
values: list[float] = []
bad_lines: list[tuple[int, str]] = []
with Path("data/readings.txt").open(encoding="utf-8") as f:
for line_number, line in ...: # TODO: enumerate from 1
... # TODO: try float(line); on ValueError keep (line_number, line.strip())
# TODO: print the count, the mean with 2 decimals and the bad lines
Hint 1

enumerate(f, start=1) numbers the lines of a file object from 1.

Hint 2

Keep only float(line) inside try. Catch ValueError, not every exception.

Solution
values: list[float] = []
bad_lines: list[tuple[int, str]] = []
with Path("data/readings.txt").open(encoding="utf-8") as f:
for line_number, line in enumerate(f, start=1):
try:
value = float(line)
except ValueError:
bad_lines.append((line_number, line.strip()))
else:
values.append(value)
print(f"{len(values)} valid readings, mean {sum(values) / len(values):.2f}")
print("Bad lines:", bad_lines)
assert len(values) + len(bad_lines) == 43
assert [n for n, _ in bad_lines] == [12, 24, 35]
Output
40 valid readings, mean 21.06
Bad lines: [(12, 'error'), (24, ''), (35, 'n/a')]

How it works:

  1. float() ignores the trailing line break and raises ValueError for error, the empty line and n/a.
  2. The else clause runs only when float() succeeded. It keeps the append() out of the try, so an error there would not be mistaken for a bad line.
  3. line.strip() removes the line break, so the report shows '' for the empty line.

Alternative: values = [float(line) for line in lines if line.strip() and line.strip() != "error" ...] is the LBYL version, and it needs to know every bad token in advance. EAFP lets float() decide.

M13-C06 · Choose a style for four parsing tasks

Section titled “M13-C06 · Choose a style for four parsing tasks”
Core

Choose a method and justify it: for each task, choose LBYL, EAFP or dict.get(), write the function and give a one-sentence reason.

  1. count_blank_lines(path): count the blank lines of data/readings.txt.
  2. parse_quantity(text): return int(text), or None for text such as "three".
  3. phone_of(customer): the phone of a record in data/customers.json, or "no phone".
  4. row_count(path): the number of data rows of a monthly report, or None if the file does not exist.
Expected output
1
[3, None, 12]
['+1-555-908-5284', 'no phone']
[55, None]
Starter
def count_blank_lines(path: Path) -> int: ... # TODO
def parse_quantity(text: str) -> int | None: ... # TODO
def phone_of(customer: dict[str, Any]) -> str: ... # TODO
def row_count(path: Path) -> int | None: ... # TODO
customers = json.loads(Path("data/customers.json").read_text(encoding="utf-8"))
# TODO: print the results for readings.txt, ["3", "three", " 12 "],
# the first two customers, 2024-06.csv and 2024-07.csv
Hint 1

Ask two questions for each task. Is the check cheap, exact and the same as the operation? Could the world change between the check and the operation?

Hint 2

Path.open() raises FileNotFoundError for a missing file. int() raises ValueError.

Solution
def count_blank_lines(path: Path) -> int:
# LBYL: a blank line is common, and `not line.strip()` is an exact, cheap test.
with path.open(encoding="utf-8") as f:
return sum(not line.strip() for line in f)
def parse_quantity(text: str) -> int | None:
# EAFP: only int() knows every valid form (" 12 ", "+3", "1_000").
try:
return int(text)
except ValueError:
return None
def phone_of(customer: dict[str, Any]) -> str:
# dict.get(): an optional key with a default needs neither if nor try.
return customer.get("phone") or "no phone"
def row_count(path: Path) -> int | None:
# EAFP: the file can disappear between an exists() check and open().
try:
with path.open(encoding="utf-8") as f:
return sum(1 for _ in f) - 1 # minus the header line
except FileNotFoundError:
return None
customers = json.loads(Path("data/customers.json").read_text(encoding="utf-8"))
print(count_blank_lines(Path("data/readings.txt")))
print([parse_quantity(t) for t in ["3", "three", " 12 "]])
print([phone_of(c) for c in customers["customers"][:2]])
print([row_count(Path(f"data/reports/2024-0{month}.csv")) for month in (6, 7)])
assert parse_quantity("three") is None
assert row_count(Path("data/reports/2024-06.csv")) == 55
Output
1
[3, None, 12]
['+1-555-908-5284', 'no phone']
[55, None]

How it works:

  1. Blank lines (LBYL). The test not line.strip() is the definition of a blank line, so the check cannot drift from the operation.
  2. Quantity (EAFP). int() accepts spaces, a sign and underscores. An LBYL check such as text.isdigit() would reject " 12 ".
  3. Phone (get). customer.get("phone") returns None for a missing key and for a null value; or replaces both.
  4. File (EAFP). if path.exists(): open(...) has a race condition, and a missing file is an exceptional case, not the normal one.

Alternative: for task 4, path.is_file() before opening is acceptable in a one-off script that nobody else runs at the same time. In a service or a shared folder, prefer EAFP.

M13-C07 · Check monthly totals: == or isclose

Section titled “M13-C07 · Check monthly totals: == or isclose”
Core

Interpret a result: the data dictionary lists the revenue sum of each monthly report. Recompute each sum with a running total (total += ...) and compare it with the listed value, once with == and once with math.isclose(). Print one line per month. Then explain why only January passes ==, and which test a pipeline should use.

Expected output
2024-01: 14162.33 ==: True isclose: True
2024-02: 4719.039999999997 ==: False isclose: True
2024-03: 12296.719999999994 ==: False isclose: True
2024-04: 10879.039999999992 ==: False isclose: True
2024-05: 6675.859999999994 ==: False isclose: True
2024-06: 8533.399999999992 ==: False isclose: True
Starter
listed = {
"2024-01": 14162.33, "2024-02": 4719.04, "2024-03": 12296.72,
"2024-04": 10879.04, "2024-05": 6675.86, "2024-06": 8533.40,
}
for path in sorted(Path("data/reports").glob("*.csv")):
total = 0.0
# TODO: add float(row["revenue"]) for each row with +=
# TODO: print stem, repr(total), total == listed, math.isclose(total, listed)
Hint 1

repr(total) shows all the digits of the float, so you can see the tiny error.

Solution
listed = {
"2024-01": 14162.33,
"2024-02": 4719.04,
"2024-03": 12296.72,
"2024-04": 10879.04,
"2024-05": 6675.86,
"2024-06": 8533.40,
}
results = {}
for path in sorted(Path("data/reports").glob("*.csv")):
total = 0.0
with path.open(newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
total += float(row["revenue"])
exact = total == listed[path.stem]
close = math.isclose(total, listed[path.stem])
results[path.stem] = (exact, close)
print(f"{path.stem}: {total!r:<20} ==: {exact!s:<5} isclose: {close}")
assert all(close for _, close in results.values())
assert sum(exact for exact, _ in results.values()) == 1
Output
2024-01: 14162.33 ==: True isclose: True
2024-02: 4719.039999999997 ==: False isclose: True
2024-03: 12296.719999999994 ==: False isclose: True
2024-04: 10879.039999999992 ==: False isclose: True
2024-05: 6675.859999999994 ==: False isclose: True
2024-06: 8533.399999999992 ==: False isclose: True

How it works:

  1. Each += rounds the running total to the nearest float. Over about 50 additions, the tiny errors add up to a few trillionths of a dollar.
  2. January happens to land exactly on the float closest to 14162.33. That is luck, not correctness: change the order of the rows and it could fail too.
  3. math.isclose() accepts a relative difference of 1e-09, about 0.00001 USD on 10,000 USD. All six months pass.
  4. A pipeline should use math.isclose(), or compare rounded cents: round(total, 2) == listed[...]. For a ledger that must be exact, sum Decimal values.

Alternative: sum(float(row["revenue"]) for row in ...) uses compensated summation (Python 3.12 and later) and gives 4719.04 exactly for February. It still is not a reason to use == on floats.

Core

Order O013624 in data/sales.csv has three lines, all with a 10% discount. Price each line with Decimal, rounded half up to the cent, and the order total. Also show the float result of round() for each line, and mark the line where the two differ.

Expected output
Fitness Tracker exact 179.982 Decimal 179.98 float 179.98
Adjustable Dumbbells exact 251.100 Decimal 251.10 float 251.1
Electric Toothbrush exact 269.955 Decimal 269.96 float 269.95 <- differs
Order total: 701.04
Starter
CENT = Decimal("0.01")
order = [
("Fitness Tracker", "99.99", 2, "0.1"),
("Adjustable Dumbbells", "279.00", 1, "0.1"),
("Electric Toothbrush", "59.99", 5, "0.1"),
]
# TODO: for each line, compute the Decimal amount (quantize, ROUND_HALF_UP)
# TODO: and the float amount with round(); print both and mark differences
# TODO: print the Decimal total
Hint 1

(Decimal(price) * qty * (1 - Decimal(disc))).quantize(CENT, rounding=ROUND_HALF_UP).

Hint 2

Compare the two by converting the float: Decimal(str(float_amount)) != amount, or compare float(amount) != float_amount.

Solution
CENT = Decimal("0.01")
order = [
("Fitness Tracker", "99.99", 2, "0.1"),
("Adjustable Dumbbells", "279.00", 1, "0.1"),
("Electric Toothbrush", "59.99", 5, "0.1"),
]
total = Decimal("0")
differences = 0
for product, price, qty, disc in order:
exact = Decimal(price) * qty * (1 - Decimal(disc))
amount = exact.quantize(CENT, rounding=ROUND_HALF_UP)
float_amount = round(float(price) * qty * (1 - float(disc)), 2)
mark = " <- differs" if float(amount) != float_amount else ""
differences += bool(mark)
total += amount
print(f"{product:<21} exact {exact:<9} Decimal {amount:>7}", end="")
print(f" float {float_amount:>7}{mark}")
print(f"Order total: {total}")
assert total == Decimal("701.04")
assert differences == 1
Output
Fitness Tracker exact 179.982 Decimal 179.98 float 179.98
Adjustable Dumbbells exact 251.100 Decimal 251.10 float 251.1
Electric Toothbrush exact 269.955 Decimal 269.96 float 269.95 <- differs
Order total: 701.04

How it works:

  1. Decimal(price) * qty is exact, because both come from text and integers. The exact column shows the unrounded amounts.
  2. 269.955 is exactly halfway. ROUND_HALF_UP rounds it to 269.96. The float product is stored as slightly less than 269.955, so round() gives 269.95.
  3. The total is the sum of the rounded lines, as an invoice shows it.

Alternative: the decimal module has other rounding rules. ROUND_HALF_EVEN (“banker’s rounding”) rounds a half to the neighbor with an even last digit: 269.955 becomes 269.96, but 85.025 becomes 85.02. Ask the finance team which rule applies, and pass it explicitly.

M13-C09 · Refactor: os.path and manual close to pathlib

Section titled “M13-C09 · Refactor: os.path and manual close to pathlib”
Core

Refactor: rows_per_file() counts the data rows of each CSV file in data/reports/. Rewrite it with pathlib, glob(), with and a dict comprehension, with a helper count_rows(path). Keep the old function in your script and assert that both return the same dict (a characterization check).

Expected output
{'2024-01': 48, '2024-02': 48, '2024-03': 47, '2024-04': 52, '2024-05': 47, '2024-06': 55}
Starter
import os
def rows_per_file(folder):
result = {}
for name in os.listdir(folder):
if name.endswith(".csv"):
f = open(os.path.join(folder, name))
n = len(f.readlines()) - 1
f.close()
result[name.replace(".csv", "")] = n
return result
# TODO: count_rows(path) and rows_per_file_v2(folder) with pathlib
Hint 1

folder.glob("*.csv") yields Path objects for the CSV files only. path.stem is the name without .csv.

Hint 2

sum(1 for _ in f) counts the lines of an open file without building a list.

Solution
import os
def rows_per_file(folder):
result = {}
for name in os.listdir(folder):
if name.endswith(".csv"):
f = open(os.path.join(folder, name))
n = len(f.readlines()) - 1
f.close()
result[name.replace(".csv", "")] = n
return result
def count_rows(path: Path) -> int:
"""Return the number of data rows, without the header line."""
with path.open(encoding="utf-8") as f:
return sum(1 for _ in f) - 1
def rows_per_file_v2(folder: Path) -> dict[str, int]:
return {path.stem: count_rows(path) for path in sorted(folder.glob("*.csv"))}
counts = rows_per_file_v2(Path("data/reports"))
print(counts)
assert counts == rows_per_file("data/reports")
assert sum(counts.values()) == 297
Output
{'2024-01': 48, '2024-02': 48, '2024-03': 47, '2024-04': 52, '2024-05': 47, '2024-06': 55}

How it works:

  1. glob("*.csv") replaces listdir() plus the endswith() filter.
  2. with closes each file, even if a read fails. open() with no with leaks the file handle on an error.
  3. path.stem replaces name.replace(".csv", ""), which would also damage a name such as sales.csv_backup.csv.
  4. sorted() gives a fixed order. The two dicts compare equal in any order, but the printed output must be stable.
  5. The solution block is marked nolint only because it keeps the old function for the check.

Alternative: len(path.read_text(encoding="utf-8").splitlines()) - 1 reads the whole file at once. That is fine for small files, but the generator version uses constant memory.

M13-C10 · Refactor: flag loops to any, all and sum

Section titled “M13-C10 · Refactor: flag loops to any, all and sum”
Core

Refactor: the validation below runs three loops over data/customers.csv with flags and counters. Replace each loop with all(), any() or sum() and a generator expression. Print the same three results.

Expected output
All ids start with C: True
Some total_charges are blank: True
Customers with 60+ months: 401
Starter
with Path("data/customers.csv").open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
ids_ok = True
for r in rows:
if not r["customer_id"].startswith("C"):
ids_ok = False
break
has_blank_total = False
for r in rows:
if r["total_charges"] == "":
has_blank_total = True
long_tenure = 0
for r in rows:
if int(r["tenure_months"]) >= 60:
long_tenure = long_tenure + 1
# TODO: three one-line versions with all(), any() and sum()
Hint 1

The first loop sets the flag to False as soon as one id fails. That is what all() does.

Hint 2

r["total_charges"] == "" can be written not r["total_charges"].

Solution
with Path("data/customers.csv").open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
ids_ok = all(r["customer_id"].startswith("C") for r in rows)
has_blank_total = any(not r["total_charges"] for r in rows)
long_tenure = sum(int(r["tenure_months"]) >= 60 for r in rows)
print(f"All ids start with C: {ids_ok}")
print(f"Some total_charges are blank: {has_blank_total}")
print(f"Customers with 60+ months: {long_tenure}")
assert len(rows) == 5000 and ids_ok and has_blank_total
Output
All ids start with C: True
Some total_charges are blank: True
Customers with 60+ months: 401

How it works:

  1. all() stops at the first id that fails, like the break in the original.
  2. any() stops at the first blank. The original loop kept reading all 5,000 rows after it found one.
  3. sum() of booleans counts the True values.
  4. The data dictionary says that 10 brand-new customers have a blank total_charges, so has_blank_total is True.

Alternative: Counter(int(r["tenure_months"]) >= 60 for r in rows)[True] also counts, but sum() says it more directly.

Core

The script orders_messy.py counts the orders of 100 USD or more per customer in data/customers.json. It runs correctly:

orders_messy.py
import json, os
from typing import Optional
def count_big_orders(path, min_amount = 100.0):
f = open(path)
data = json.load(f)
f.close()
counts = {}
for c in data["customers"]:
if c.get("orders") == None: continue
for o in c["orders"]:
if o["amount"] >= min_amount:
counts[c["customer_id"]] = counts.get(c["customer_id"], 0) + 1
return counts
def top_customer(counts: dict) -> Optional[str]:
if len(counts) == 0:
return None
return max(counts, key=counts.get)
counts = count_big_orders(os.path.join("data", "customers.json"))
print("Customers with big orders: %d" % len(counts))
print("Most big orders: %s" % top_customer(counts))
Output
Customers with big orders: 15
Most big orders: C00003

Ruff reports these findings with the module configuration:

Terminal
ruff check --output-format concise orders_messy.py
Output
orders_messy.py:1:1: E401 [*] Multiple imports on one line
orders_messy.py:1:1: I001 [*] Import block is un-sorted or un-formatted
orders_messy.py:6:9: PTH123 `open()` should be replaced by `Path.open()`
orders_messy.py:6:9: SIM115 Use a context manager for opening files
orders_messy.py:11:31: E711 Comparison to `None` should be `cond is None`
orders_messy.py:11:35: E701 Multiple statements on one line (colon)
orders_messy.py:18:35: UP045 [*] Use `X | None` for type annotations
orders_messy.py:24:27: PTH118 `os.path.join()` should be replaced by `Path` with `/` operator
orders_messy.py:25:7: UP031 Use format specifiers instead of percent format
orders_messy.py:26:7: UP031 Use format specifiers instead of percent format
Found 10 errors.
[*] 3 fixable with `--fix` (2 unsafe fixes available with `--fix --unsafe-fixes`).

Fix every finding by hand, and keep the output identical. Also use a constant for the 100 USD threshold.

Expected output
Customers with big orders: 15
Most big orders: C00003
Starter
# TODO: copy orders_messy.py and fix E401/I001, PTH123/SIM115/PTH118,
# E711/E701, UP045 and UP031. Keep both printed lines identical.
Hint 1

Path.read_text() plus json.loads() replaces open(), json.load() and close(), and needs no with.

Hint 2

Optional[str] becomes str | None. "... %d" % n becomes f"... {n}". The == None test on orders can go: every record has an orders list, and iterating an empty list does nothing.

Solution
BIG_ORDER_USD = 100.0
def count_big_orders(path: Path, min_amount: float = BIG_ORDER_USD) -> dict[str, int]:
"""Count the orders of at least `min_amount` per customer id."""
data = json.loads(path.read_text(encoding="utf-8"))
counts: dict[str, int] = {}
for customer in data["customers"]:
for order in customer["orders"]:
if order["amount"] >= min_amount:
customer_id = customer["customer_id"]
counts[customer_id] = counts.get(customer_id, 0) + 1
return counts
def top_customer(counts: dict[str, int]) -> str | None:
"""Return the id with the most big orders, or None for no data."""
if not counts:
return None
return max(counts, key=counts.get)
counts = count_big_orders(Path("data") / "customers.json")
print(f"Customers with big orders: {len(counts)}")
print(f"Most big orders: {top_customer(counts)}")
assert top_customer({}) is None
assert counts[top_customer(counts)] == max(counts.values())
Output
Customers with big orders: 15
Most big orders: C00003

How it works:

  1. E401, I001: the imports are gone from the solution, because the page setup imports json and Path. In your own script, write import json and from pathlib import Path on two lines.
  2. PTH123, SIM115, PTH118: Path("data") / "customers.json" and read_text() replace os.path.join(), open() and close().
  3. E711, E701: the == None test was never needed, so it is gone instead of fixed.
  4. UP045, UP031: str | None and f-strings.
  5. Not a ruff rule: c and o became customer and order, and BIG_ORDER_USD names the threshold.

Alternative: Counter(c["customer_id"] for c in data["customers"] for o in c["orders"] if o["amount"] >= min_amount) counts in one expression, and counts.most_common(1) finds the top customer.

M13-C12 · Refactor: untangle a clever comprehension

Section titled “M13-C12 · Refactor: untangle a clever comprehension”
Core

Refactor: this one-line dict comprehension finds, for each premium customer tagged vip in data/customers.json, the orders above 100 USD with more than one item. It works, but nobody can review it. Split it into two named helper functions and a short comprehension. The result must be equal.

Expected output
{'C00003': ['O001975'], 'C00004': ['O007106']}
Starter
data = json.loads(Path("data/customers.json").read_text(encoding="utf-8"))
result = {c["customer_id"]: [o["order_id"] for o in c["orders"] if o["amount"] > 100 and o["items"] > 1] for c in data["customers"] if c["plan"] == "premium" and c["orders"] and any(t == "vip" for t in c["tags"])}
print(result)
# TODO: is_premium_vip(customer), big_multi_item_orders(customer), then a short comprehension
Hint 1

Two conditions hide in the comprehension: one selects customers, one selects orders. Give each a function with a name.

Hint 2

any(t == "vip" for t in c["tags"]) is just "vip" in c["tags"].

Solution
data = json.loads(Path("data/customers.json").read_text(encoding="utf-8"))
def is_premium_vip(customer: dict[str, Any]) -> bool:
"""A premium customer with the vip tag and at least one order."""
return (
customer["plan"] == "premium"
and "vip" in customer["tags"]
and bool(customer["orders"])
)
def big_multi_item_orders(customer: dict[str, Any]) -> list[str]:
"""Ids of the orders above 100 USD with more than one item."""
return [
order["order_id"]
for order in customer["orders"]
if order["amount"] > 100 and order["items"] > 1
]
result = {
c["customer_id"]: big_multi_item_orders(c)
for c in data["customers"]
if is_premium_vip(c)
}
print(result)
assert all(isinstance(ids, list) for ids in result.values())
assert result == {
c["customer_id"]: [
o["order_id"] for o in c["orders"] if o["amount"] > 100 and o["items"] > 1
]
for c in data["customers"]
if c["plan"] == "premium" and c["orders"] and any(t == "vip" for t in c["tags"])
}
Output
{'C00003': ['O001975'], 'C00004': ['O007106']}

How it works:

  1. Each helper has one job, a name that says what it selects and a docstring. A reviewer can check each rule on its own.
  2. "vip" in customer["tags"] replaces the any() with a membership test.
  3. The final comprehension has one for and one if, and it reads like the task: “for each premium vip customer, their big multi-item orders”.
  4. The last assert keeps the original expression as a characterization check.

Alternative: a plain loop with if not is_premium_vip(c): continue reads equally well. Choose the comprehension when the body is one expression.

M13-C13 · Predict the output: five gotchas

Section titled “M13-C13 · Predict the output: five gotchas”
Core

Predict the output: each line of this script shows one of the five gotchas of the lesson. Write down what each print() shows, then run the code.

Acceptance criteria:

  • Write your prediction for every line before you run the code.
  • Run the code. Your prediction matches the Output in the solution, line by line.
  • For each line, you can name the gotcha and its fix.
Starter
def tag(item, tags=[]):
tags.append(item)
return tags
tag("vip")
print(tag("new"))
funcs = [lambda: n for n in range(3)]
print([f() for f in funcs])
status = "-".join(["no", "data"])
print(status == "no-data", status is "no-data")
print(0.1 * 3 == 0.3, math.isclose(0.1 * 3, 0.3))
codes = [-999, -999, -999, 21]
for c in codes:
if c == -999:
codes.remove(c)
print(codes)
# TODO: write your prediction for each line before you run it
Hint 1

Lines 1 and 2: defaults are evaluated once, and closures look up names late.

Hint 2

Line 5: count how many -999 values the loop really visits.

Solution

The solution compares with a constant instead of the literal "no-data", because is with a literal gives a SyntaxWarning. The result is the same.

def tag(item, tags=[]):
tags.append(item)
return tags
tag("vip")
print(tag("new"))
funcs = [lambda: n for n in range(3)]
print([f() for f in funcs])
NO_DATA = "no-data"
status = "-".join(["no", "data"])
print(status == NO_DATA, status is NO_DATA)
print(0.1 * 3 == 0.3, math.isclose(0.1 * 3, 0.3))
codes = [-999, -999, -999, 21]
for c in codes:
if c == -999:
codes.remove(c)
print(codes)
assert tag("x") == ["vip", "new", "x"]
assert [f() for f in funcs] == [2, 2, 2]
assert codes == [-999, 21]
Output
['vip', 'new']
[2, 2, 2]
True False
False True
[-999, 21]

How it works:

  1. Mutable default. Both calls share one list, so it holds vip and new. Fix: tags=None.
  2. Late binding. The three lambdas share n, which is 2 after the comprehension. Fix: lambda n=n: n.
  3. Identity. join() builds a new string. It is equal to "no-data", not the same object. Fix: ==.
  4. Float precision. 0.1 * 3 is 0.30000000000000004. Fix: math.isclose().
  5. Changing a list during a loop. The loop sees -999 at position 0 and removes it. At position 1 it sees another -999 and calls remove(), which deletes the first -999 in the list. Now the list has only 2 items, so the loop stops before position 2. One code survives. Fix: [c for c in codes if c != -999].

Alternative: run ruff check --select B on the starter. It reports B006 for line 1 and B023 for the lambda. The other three need your eyes.

M13-X01 · Parse a gateway batch file end to end

Section titled “M13-X01 · Parse a gateway batch file end to end”
Challenge

A sensor gateway sent six batch lines in the format sensor;status;readings. Readings are comma-separated. -999.0 is the “no reading” code, and some readings are corrupt text. Write parse_line() (EAFP for the numbers, no list changed during a loop), then a report per sensor: kept readings, dropped codes, corrupt values and the mean of the kept readings. End with the status counts and the sensors that ever reported warn or fail.

Expected output
S1: kept 5, dropped 1, corrupt 0, mean 20.29 C
S2: kept 4, dropped 2, corrupt 0, mean 26.28 C
S3: kept 2, dropped 0, corrupt 1, mean 19.25 C
S4: kept 2, dropped 1, corrupt 0, mean 24.37 C
Statuses: {'ok': 4, 'warn': 1, 'fail': 1}
Sensors with warn or fail: ['S2', 'S4']
Starter
MISSING = -999.0
batch = [
"S1;ok;20.21,20.18,-999.0,20.4",
"S2;warn;22.3,38.03,-999.0,-999.0",
"S3;ok;19.4,err,19.11",
"S4;fail;24.52,24.22,-999.0",
"S1;ok;20.35,20.29",
"S2;ok;22.41,22.38",
]
# TODO: parse_line(line) -> (sensor_id, status, kept, dropped, corrupt)
# TODO: combine the lines per sensor; print one line per sensor
# TODO: print the status counts and the sensors with warn or fail
Hint 1

Split the line with unpacking: sensor_id, status, raw = line.split(";"). Then loop over raw.split(",") and append each value to one of three lists.

Hint 2

Keep one defaultdict(list) for kept readings and two Counter objects for dropped and corrupt counts.

Hint 3

{s for s, status in ... if status in {"warn", "fail"}} is a set comprehension. Print it with sorted().

Solution
MISSING = -999.0
ALERT_STATUSES = {"warn", "fail"}
batch = [
"S1;ok;20.21,20.18,-999.0,20.4",
"S2;warn;22.3,38.03,-999.0,-999.0",
"S3;ok;19.4,err,19.11",
"S4;fail;24.52,24.22,-999.0",
"S1;ok;20.35,20.29",
"S2;ok;22.41,22.38",
]
def parse_line(line: str) -> tuple[str, str, list[float], int, int]:
"""Return the id, status, kept readings, dropped count and corrupt count."""
sensor_id, status, raw = line.split(";")
kept: list[float] = []
dropped = corrupt = 0
for text in raw.split(","):
try:
value = float(text)
except ValueError:
corrupt += 1
continue
if value == MISSING:
dropped += 1
else:
kept.append(value)
return sensor_id, status, kept, dropped, corrupt
kept_by_sensor: defaultdict[str, list[float]] = defaultdict(list)
dropped_by_sensor: Counter[str] = Counter()
corrupt_by_sensor: Counter[str] = Counter()
statuses: Counter[str] = Counter()
alerted: set[str] = set()
for line in batch:
sensor_id, status, kept, dropped, corrupt = parse_line(line)
kept_by_sensor[sensor_id].extend(kept)
dropped_by_sensor[sensor_id] += dropped
corrupt_by_sensor[sensor_id] += corrupt
statuses[status] += 1
if status in ALERT_STATUSES:
alerted.add(sensor_id)
for sensor_id, values in sorted(kept_by_sensor.items()):
mean = sum(values) / len(values)
print(
f"{sensor_id}: kept {len(values)}, dropped {dropped_by_sensor[sensor_id]}, "
f"corrupt {corrupt_by_sensor[sensor_id]}, mean {mean:.2f} C"
)
print("Statuses:", dict(statuses.most_common()))
print("Sensors with warn or fail:", sorted(alerted))
assert sum(dropped_by_sensor.values()) == 4
assert corrupt_by_sensor["S3"] == 1
assert sorted(alerted) == ["S2", "S4"]
Output
S1: kept 5, dropped 1, corrupt 0, mean 20.29 C
S2: kept 4, dropped 2, corrupt 0, mean 26.28 C
S3: kept 2, dropped 0, corrupt 1, mean 19.25 C
S4: kept 2, dropped 1, corrupt 0, mean 24.37 C
Statuses: {'ok': 4, 'warn': 1, 'fail': 1}
Sensors with warn or fail: ['S2', 'S4']

How it works:

  1. parse_line() keeps float() alone in the try. A corrupt value is counted and skipped with continue. The -999.0 check comes after the parse, as a plain LBYL business rule.
  2. The function never removes from a list. It sorts each value into the right bucket on the first pass.
  3. The function returns counts instead of filling a shared list, so it has no mutable default and no hidden state.
  4. Implicit concatenation of two f-strings keeps the long print() under 88 characters.
  5. S2’s mean includes the spike 38.03. A real pipeline would flag it too (module 26).

Alternative: return a small dataclass instead of a 5-item tuple (module 21). Then the caller writes result.kept instead of unpacking five names in the right order.

M13-X02 · Refactor a plan report behind a characterization check

Section titled “M13-X02 · Refactor a plan report behind a characterization check”
Challenge

Refactor: plan_report_before() summarizes data/customers.json per plan: customers, orders, order revenue and customers without orders. It works, but it hides meaning in list positions (plans[p][2]). Refactor it into plan_report() with Counter, defaultdict and f-strings. Keep the old function as a characterization check: both must return the same lines. Then make one deliberate improvement in a separate function, plan_report_v2(): show the revenue with a thousands separator. Print the lines that it changes.

Expected output
basic: 7 customers, 21 orders, revenue 5629.30, 0 without orders
premium: 6 customers, 14 orders, revenue 4187.06, 1 without orders
standard: 7 customers, 13 orders, revenue 3895.34, 2 without orders
Changed by v2:
basic: 7 customers, 21 orders, revenue 5629.30, 0 without orders
basic: 7 customers, 21 orders, revenue 5,629.30, 0 without orders
premium: 6 customers, 14 orders, revenue 4187.06, 1 without orders
premium: 6 customers, 14 orders, revenue 4,187.06, 1 without orders
standard: 7 customers, 13 orders, revenue 3895.34, 2 without orders
standard: 7 customers, 13 orders, revenue 3,895.34, 2 without orders
Starter
def plan_report_before(path):
f = open(path)
data = json.load(f)
f.close()
plans = {}
for c in data["customers"]:
p = c["plan"]
if p not in plans:
plans[p] = [0, 0, 0.0, 0]
plans[p][0] += 1
plans[p][1] += len(c["orders"])
for o in c["orders"]:
plans[p][2] += o["amount"]
if len(c["orders"]) == 0:
plans[p][3] += 1
lines = []
for p in sorted(plans):
lines.append(p + ": " + str(plans[p][0]) + " customers, " + str(plans[p][1])
+ " orders, revenue " + "%.2f" % plans[p][2] + ", "
+ str(plans[p][3]) + " without orders")
return lines
# TODO: expected = plan_report_before("data/customers.json")
# TODO: plan_report(path) with Counter/defaultdict; assert it equals expected
# TODO: plan_report_v2(path) with revenue as 5,629.30; print the changed lines
Hint 1

Use four collections with names: customers = Counter(), orders = Counter(), revenue = defaultdict(float), without_orders = Counter().

Hint 2

revenue[plan] += sum(o["amount"] for o in c["orders"]) replaces the inner loop. without_orders[plan] += not c["orders"] adds 1 for an empty list.

Hint 3

Put the counting in one helper that returns the four collections. Then plan_report() and plan_report_v2() differ only in the format spec: :.2f and :,.2f. Compare the old and new lines with zip(..., strict=True) and print only the pairs that differ.

Solution
def plan_report_before(path):
f = open(path)
data = json.load(f)
f.close()
plans = {}
for c in data["customers"]:
p = c["plan"]
if p not in plans:
plans[p] = [0, 0, 0.0, 0]
plans[p][0] += 1
plans[p][1] += len(c["orders"])
for o in c["orders"]:
plans[p][2] += o["amount"]
if len(c["orders"]) == 0:
plans[p][3] += 1
lines = []
for p in sorted(plans):
lines.append(p + ": " + str(plans[p][0]) + " customers, " + str(plans[p][1])
+ " orders, revenue " + "%.2f" % plans[p][2] + ", "
+ str(plans[p][3]) + " without orders")
return lines
PlanTotals = tuple[Counter[str], Counter[str], defaultdict[str, float], Counter[str]]
def plan_totals(path: Path) -> PlanTotals:
"""Return customers, orders, revenue and customers without orders, per plan."""
data = json.loads(path.read_text(encoding="utf-8"))
customers: Counter[str] = Counter()
orders: Counter[str] = Counter()
revenue: defaultdict[str, float] = defaultdict(float)
without_orders: Counter[str] = Counter()
for c in data["customers"]:
plan = c["plan"]
customers[plan] += 1
orders[plan] += len(c["orders"])
revenue[plan] += sum(o["amount"] for o in c["orders"])
without_orders[plan] += not c["orders"]
return customers, orders, revenue, without_orders
def plan_report(path: Path) -> list[str]:
customers, orders, revenue, without_orders = plan_totals(path)
return [
f"{plan}: {customers[plan]} customers, {orders[plan]} orders, "
f"revenue {revenue[plan]:.2f}, {without_orders[plan]} without orders"
for plan in sorted(customers)
]
def plan_report_v2(path: Path) -> list[str]:
"""The same report, with a thousands separator in the revenue."""
customers, orders, revenue, without_orders = plan_totals(path)
return [
f"{plan}: {customers[plan]} customers, {orders[plan]} orders, "
f"revenue {revenue[plan]:,.2f}, {without_orders[plan]} without orders"
for plan in sorted(customers)
]
path = Path("data/customers.json")
expected = plan_report_before(path)
print("\n".join(plan_report(path)))
assert plan_report(path) == expected
print("Changed by v2:")
for old, new in zip(expected, plan_report_v2(path), strict=True):
if old != new:
print(f" {old}\n {new}")
assert plan_report_v2(path) != expected
Output
basic: 7 customers, 21 orders, revenue 5629.30, 0 without orders
premium: 6 customers, 14 orders, revenue 4187.06, 1 without orders
standard: 7 customers, 13 orders, revenue 3895.34, 2 without orders
Changed by v2:
basic: 7 customers, 21 orders, revenue 5629.30, 0 without orders
basic: 7 customers, 21 orders, revenue 5,629.30, 0 without orders
premium: 6 customers, 14 orders, revenue 4187.06, 1 without orders
premium: 6 customers, 14 orders, revenue 4,187.06, 1 without orders
standard: 7 customers, 13 orders, revenue 3895.34, 2 without orders
standard: 7 customers, 13 orders, revenue 3,895.34, 2 without orders

How it works:

  1. Four named collections replace the list [0, 0, 0.0, 0]. orders[plan] says what plans[p][1] only implied.
  2. sum(o["amount"] for o in c["orders"]) replaces the inner loop. For an empty list it is 0.
  3. without_orders[plan] += not c["orders"] adds True (1) for an empty list and False (0) otherwise.
  4. plan_totals() does the counting once, and the two report functions only format. That split makes the v2 change small.
  5. The characterization assert passes before the improvement. The improvement is a separate, visible step, and the comparison shows every line it changes. In a real project, you would now update the recorded output on purpose.
  6. The summing differs: the legacy code adds each order to the plan total, while plan_totals() first sums each customer’s orders with sum() (compensated summation) and then adds that. The raw floats can differ in the last digits; rounding to 2 decimals hides that here. A robust check compares the raw totals with math.isclose().

Alternative: put the four numbers in a dataclass PlanStats (module 21) and keep a dict[str, PlanStats]. Then each plan’s numbers travel together.

M13-X03 · Build rule checks from the config without late binding

Section titled “M13-X03 · Build rule checks from the config without late binding”
Challenge

data/config.json holds the quality thresholds for data/sales_raw.csv. Build one check function per rule in a loop, without the late-binding bug of the starter. Parse the numbers in EAFP style, with the config’s missing-value tokens. Count per rule: violations and unparsable values. Then count the rows that break at least one rule.

Expected output
quantity < min_quantity (1): 6 violations, 0 unparsable
quantity > max_quantity (50): 4 violations, 0 unparsable
discount > max_discount (0.2): 0 violations, 24 unparsable
Rows breaking any rule: 10 of 1200
Starter
import operator
config = json.loads(Path("data/config.json").read_text(encoding="utf-8"))
limits = config["thresholds"]
RULES = [
("quantity < min_quantity", "quantity", operator.lt, limits["min_quantity"]),
("quantity > max_quantity", "quantity", operator.gt, limits["max_quantity"]),
("discount > max_discount", "discount", operator.gt, limits["max_discount"]),
]
checks = {}
for name, column, compare, limit in RULES:
checks[name] = lambda value: compare(value, limit) # late binding!
# TODO: make_check(compare, limit); parse_number(text) with EAFP and na_values
# TODO: read the rows; count violations and unparsable values per rule
# TODO: count the rows that break any rule
Hint 1

All three lambdas of the starter use the last compare and limit: operator.gt and 0.2. Write make_check(compare, limit) that returns an inner function.

Hint 2

parse_number(text) returns None for a token in config["cleaning"]["na_values"] and for text that float() rejects.

Hint 3

Keep the column name next to each check: checks[name] = (column, make_check(compare, limit)). For “any rule”, use any() over the checks of one row.

Solution
import operator
from collections.abc import Callable
config = json.loads(Path("data/config.json").read_text(encoding="utf-8"))
limits = config["thresholds"]
NA_VALUES = set(config["cleaning"]["na_values"])
RULES = [
("quantity < min_quantity", "quantity", operator.lt, limits["min_quantity"]),
("quantity > max_quantity", "quantity", operator.gt, limits["max_quantity"]),
("discount > max_discount", "discount", operator.gt, limits["max_discount"]),
]
def make_check(
compare: Callable[[float, float], bool], limit: float
) -> Callable[[float], bool]:
def check(value: float) -> bool:
return compare(value, limit)
return check
def parse_number(text: str) -> float | None:
if text in NA_VALUES:
return None
try:
return float(text)
except ValueError:
return None
checks = {name: (column, make_check(op, limit)) for name, column, op, limit in RULES}
with Path("data/sales_raw.csv").open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
violations: Counter[str] = Counter()
unparsable: Counter[str] = Counter()
for row in rows:
for name, (column, check) in checks.items():
value = parse_number(row[column])
if value is None:
unparsable[name] += 1
elif check(value):
violations[name] += 1
def breaks_any_rule(row: dict[str, str]) -> bool:
parsed = [(parse_number(row[column]), check) for column, check in checks.values()]
return any(value is not None and check(value) for value, check in parsed)
for name, _, _, limit in RULES:
print(f"{name} ({limit}): {violations[name]} violations, ", end="")
print(f"{unparsable[name]} unparsable")
broken = sum(breaks_any_rule(row) for row in rows)
print(f"Rows breaking any rule: {broken} of {len(rows)}")
assert violations["discount > max_discount"] == 0
max_check = checks["quantity > max_quantity"][1]
assert max_check(51) and not max_check(50)
Output
quantity < min_quantity (1): 6 violations, 0 unparsable
quantity > max_quantity (50): 4 violations, 0 unparsable
discount > max_discount (0.2): 0 violations, 24 unparsable
Rows breaking any rule: 10 of 1200

How it works:

  1. make_check() creates a new scope for each rule, so each check remembers its own compare and limit. The last assert tests the boundary of one rule: 51 breaks it, 50 does not.
  2. parse_number() uses LBYL for the known missing tokens (an exact, cheap test from the config) and EAFP for everything else.
  3. The quantity rules find the 6 negative and the 4 absurd quantities that the data dictionary lists; none of these rows has a duplicate. The discount rule finds no violation, but 24 discounts are missing tokens.
  4. breaks_any_rule() parses each value once, then any() stops at the first broken rule. A missing value breaks no rule, because the None test comes first and and short-circuits.

Alternative: functools.partial() can build the checks without a factory, but only if it binds both names: partial(lambda value, compare, limit: compare(value, limit), compare=op, limit=limit). A shorter form such as partial(lambda limit, value: compare(value, limit), limit) binds limit but still reads compare late, so every check would use the last operator. make_check() is easier to read and to get right.

M13-X04 · Reconcile the revenue column with Decimal

Section titled “M13-X04 · Reconcile the revenue column with Decimal”
Challenge

Interpret a result: the finance team rounds every order line half up to the cent. Check all 20,228 lines of data/sales.csv against that rule with Decimal. Report the number of lines that differ, the set of differences, the net difference in USD and the three products with the most differing lines. Then check the same lines against ROUND_HALF_EVEN, and explain what rule the file seems to follow.

Expected output
Lines checked: 20228, differ from half up: 116
Differences: [Decimal('-0.01')]
Net difference: -1.16
Top products:
Shampoo and Conditioner Set: 52 lines
Merino Wool Sweater: 45 lines
Chef's Knife Set: 16 lines
Differ from half even: 2
Starter
from decimal import ROUND_HALF_EVEN
CENT = Decimal("0.01")
with Path("data/sales.csv").open(newline="", encoding="utf-8") as f:
sales = list(csv.DictReader(f))
# TODO: expected_amount(row, rounding) -> Decimal
# TODO: list the rows where Decimal(row["revenue"]) != expected_amount(row, ROUND_HALF_UP)
# TODO: print the counts, the set of differences, the net difference, the top 3 products
# TODO: count the mismatches with ROUND_HALF_EVEN
Hint 1

Build every Decimal from the text of the CSV: Decimal(row["unit_price"]), Decimal(row["discount"]), int(row["quantity"]).

Hint 2

Keep pairs of (row, difference). Counter(row["product"] for row, _ in diffs).most_common(3) gives the top products.

Solution
from decimal import ROUND_HALF_EVEN
CENT = Decimal("0.01")
with Path("data/sales.csv").open(newline="", encoding="utf-8") as f:
sales = list(csv.DictReader(f))
def expected_amount(row: dict[str, str], rounding: str) -> Decimal:
price = Decimal(row["unit_price"])
exact = price * int(row["quantity"]) * (1 - Decimal(row["discount"]))
return exact.quantize(CENT, rounding=rounding)
diffs = [
(row, Decimal(row["revenue"]) - expected_amount(row, ROUND_HALF_UP))
for row in sales
]
diffs = [(row, d) for row, d in diffs if d]
print(f"Lines checked: {len(sales)}, differ from half up: {len(diffs)}")
print("Differences:", sorted({d for _, d in diffs}))
print("Net difference:", sum(d for _, d in diffs))
print("Top products:")
for product, count in Counter(row["product"] for row, _ in diffs).most_common(3):
print(f" {product}: {count} lines")
half_even = sum(
Decimal(row["revenue"]) != expected_amount(row, ROUND_HALF_EVEN) for row in sales
)
print(f"Differ from half even: {half_even}")
assert all(abs(d) == CENT for _, d in diffs)
assert half_even < len(diffs)
Output
Lines checked: 20228, differ from half up: 116
Differences: [Decimal('-0.01')]
Net difference: -1.16
Top products:
Shampoo and Conditioner Set: 52 lines
Merino Wool Sweater: 45 lines
Chef's Knife Set: 16 lines
Differ from half even: 2

How it works:

  1. expected_amount() computes the exact line amount from the text, then rounds it with the rule it receives. Decimal makes the comparison exact: no tolerance is needed.
  2. The list comprehension with if d keeps only the non-zero differences, because Decimal("0") is falsy.
  3. Every difference is exactly one cent down: the file rounded those halfway amounts down.
  4. Interpretation. With half even, only 2 lines differ. So the file follows “round half to even” (NumPy’s np.round, see the data dictionary), and the 2 remaining lines are halfway amounts where the float product landed a hair above or below the half. For the finance team, 116 lines are one cent low, a net of -1.16 USD. Recompute revenue with the agreed rule before you reconcile with accounting.

Alternative: pandas can do the same check on a whole column (modules 24 and 26), but its arithmetic is float-based, so the exact half-cent cases need Decimal or integer arithmetic. With price_cents, qty and discount_pct as int, price_cents * qty * (100 - discount_pct) is exact in hundredths of a cent, and (that + 50) // 100 rounds it half up to cents. This shortcut holds for non-negative amounts only.

M13-X05 · Find and fix every gotcha in a pipeline module

Section titled “M13-X05 · Find and fix every gotcha in a pipeline module”
Challenge

Fix the bug (five of them): the module below loads gateway batches, removes -999.0 codes, counts alerts per sensor and checks calibration. It processes two days, and the numbers of both days are wrong. Find all five gotchas, fix them, and make the report for each day depend only on that day’s lines.

Expected output
S1: n=3 ok=1 alerts=0 mean=20.40 calibrated=True
S2: n=3 ok=1 alerts=1 mean=22.87 calibrated=False
S1: n=3 ok=1 alerts=2 mean=21.30 calibrated=False
S2: n=2 ok=0 alerts=2 mean=24.00 calibrated=False
Starter
SENTINEL = -999.0
OK = "ok"
TARGET_MEAN = 20.4 # calibration target for S1
def load(lines, store={}):
for line in lines:
sensor_id, status, raw = line.split(";")
entry = store.setdefault(sensor_id, {"values": [], "ok": 0})
entry["values"].extend(float(x) for x in raw.split(","))
if status is OK:
entry["ok"] += 1
return store
def make_alerts(limits):
alerts = {}
for sensor_id, limit in limits.items():
alerts[sensor_id] = lambda t: t > limit
return alerts
def clean(values):
for v in values:
if v == SENTINEL:
values.remove(v)
return values
def report(lines, limits):
store = load(lines)
alerts = make_alerts(limits)
out = []
for sensor_id, entry in sorted(store.items()):
values = clean(entry["values"])
n_alerts = sum(alerts[sensor_id](t) for t in values)
mean = sum(values) / len(values)
calibrated = mean == TARGET_MEAN
out.append(f"{sensor_id}: n={len(values)} ok={entry['ok']} "
f"alerts={n_alerts} mean={mean:.2f} calibrated={calibrated}")
return out
limits = {"S1": 21.0, "S2": 23.0}
day_1 = ["S1;ok;20.0,-999.0,-999.0,20.4,20.8", "S2;ok;22.3,23.5,22.8"]
day_2 = ["S1;ok;21.4,20.9,21.6", "S2;warn;23.9,-999.0,24.1"]
print("\n".join(report(day_1, limits)))
print("\n".join(report(day_2, limits)))
# TODO: fix the five gotchas
Hint 1

List the five gotchas of the lesson. Each function above contains at least one. report() contains one too.

Hint 2

Run the starter and check each number by hand. Day 1, S1: the clean readings are 20.0, 20.4 and 20.8, so the mean is 20.4 and S1 is calibrated. Day 1, S2: one reading is above 23.0, so there is one alert.

Hint 3

The fixes are: a None default (or no store parameter at all), a factory for the alerts, == for the status, a comprehension in clean(), and math.isclose() for the calibration.

Solution
from collections.abc import Callable
from typing import TypedDict
SENTINEL = -999.0
OK = "ok"
TARGET_MEAN = 20.4 # calibration target for S1
class Entry(TypedDict):
values: list[float]
ok: int
def load(lines: list[str]) -> dict[str, Entry]:
"""Group readings and ok-batch counts by sensor, for these lines only."""
store: dict[str, Entry] = {}
for line in lines:
sensor_id, status, raw = line.split(";")
entry = store.setdefault(sensor_id, {"values": [], "ok": 0})
entry["values"].extend(float(x) for x in raw.split(","))
if status == OK:
entry["ok"] += 1
return store
def make_alert(limit: float) -> Callable[[float], bool]:
def alert(t: float) -> bool:
return t > limit
return alert
def make_alerts(limits: dict[str, float]) -> dict[str, Callable[[float], bool]]:
return {sensor_id: make_alert(limit) for sensor_id, limit in limits.items()}
def clean(values: list[float]) -> list[float]:
return [v for v in values if v != SENTINEL]
def report(lines: list[str], limits: dict[str, float]) -> list[str]:
alerts = make_alerts(limits)
out = []
for sensor_id, entry in sorted(load(lines).items()):
values = clean(entry["values"])
n_alerts = sum(alerts[sensor_id](t) for t in values)
mean = sum(values) / len(values)
calibrated = math.isclose(mean, TARGET_MEAN)
out.append(
f"{sensor_id}: n={len(values)} ok={entry['ok']} "
f"alerts={n_alerts} mean={mean:.2f} calibrated={calibrated}"
)
return out
limits = {"S1": 21.0, "S2": 23.0}
day_1 = ["S1;ok;20.0,-999.0,-999.0,20.4,20.8", "S2;ok;22.3,23.5,22.8"]
day_2 = ["S1;ok;21.4,20.9,21.6", "S2;warn;23.9,-999.0,24.1"]
report_1 = report(day_1, limits)
report_2 = report(day_2, limits)
print("\n".join(report_1))
print("\n".join(report_2))
assert report(day_2, limits) == report_2 # no state survives between calls
assert report_1[0].endswith("calibrated=True")
assert report_2[1] == "S2: n=2 ok=0 alerts=2 mean=24.00 calibrated=False"
Output
S1: n=3 ok=1 alerts=0 mean=20.40 calibrated=True
S2: n=3 ok=1 alerts=1 mean=22.87 calibrated=False
S1: n=3 ok=1 alerts=2 mean=21.30 calibrated=False
S2: n=2 ok=0 alerts=2 mean=24.00 calibrated=False

How it works:

  1. Mutable default. store={} kept day 1 in the store, so day 2 reported both days. load() now creates its dict inside, so each call sees only its own lines.
  2. Late binding. All alert lambdas compared with the last limit, 23.0. make_alert() gives each sensor its own limit.
  3. Identity. status is OK was False for a status from split(), so ok stayed 0. == counts the ok batches.
  4. List changed during iteration. clean() skipped the second of two adjacent -999.0 codes, which then went into the mean. The comprehension removes all of them.
  5. Float equality. The mean of 20.0, 20.4 and 20.8 is 20.400000000000002, so == 20.4 was False. math.isclose() accepts it.
  6. The first assert runs the report a second time and checks that the result does not change. That test fails at once for the mutable-default bug.

Alternative: turn the module into a class with a load() method that returns a new store (module 18), or a pure function pipeline as here. In both, a function’s result depends only on its arguments, which is what makes it testable in module 14.