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:
- Read the task and the expected output.
- Copy the setup block and the starter code into a script and replace each to-do comment with your code.
- Run the script and compare your output with the expected output.
- 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 csvimport jsonimport mathfrom collections import Counter, defaultdictfrom decimal import ROUND_HALF_UP, Decimalfrom pathlib import Pathfrom typing import AnyWarm-up
Section titled “Warm-up”M13-W01 · Number the products with enumerate
Section titled “M13-W01 · Number the products with enumerate”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.
1) Wireless Earbuds2) Noise-Cancelling Headphones3) 55-inch 4K Smart TV4) 14-inch Ultrabook Laptop5) Smartwatch Series 5products = [ "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 themHint 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"1) Wireless Earbuds2) Noise-Cancelling Headphones3) 55-inch 4K Smart TV4) 14-inch Ultrabook Laptop5) Smartwatch Series 5How it works:
enumerate(products, start=1)produces a count and an item for each product. The count starts at 1, so noi + 1is needed.- The comprehension unpacks each pair into
numberandname. - 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”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.
{'S1': 20.21, 'S2': 22.3, 'S3': 19.4, 'S4': 24.52}Hottest: S4 (24.52 C)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 functionHint 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{'S1': 20.21, 'S2': 22.3, 'S3': 19.4, 'S4': 24.52}Hottest: S4 (24.52 C)How it works:
zip()pairs the two lists item by item.strict=Trueraises aValueErrorif one list is shorter, so a lost reading cannot pass unnoticed.dict()turns the pairs into a dict.- Looping over a dict gives its keys.
key=latest.getmakesmax()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.
M13-W03 · Count categories with dict.get
Section titled “M13-W03 · Count categories with dict.get”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.
Electronics: 15Sports: 11Clothing: 8Books: 5Beauty: 5Home: 4with 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 smallestHint 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) + 1for category, count in sorted(counts.items(), key=lambda item: item[1], reverse=True): print(f"{category}: {count}")assert sum(counts.values()) == len(rows) == 48Electronics: 15Sports: 11Clothing: 8Books: 5Beauty: 5Home: 4How it works:
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.sorted()withreverse=Trueputs the largest count first.sorted()is stable, so categories with the same count keep their first-seen order.- 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}")Electronics: 15Sports: 11Clothing: 8Books: 5Beauty: 5Home: 4M13-W04 · Predict the output: any, all and empty data
Section titled “M13-W04 · Predict the output: any, all and empty data”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.
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 itHint 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) == 2assert all(q >= 1 for q in empty) and not any(q > 10 for q in empty)TrueTrue2FalseTrueHow it works:
25 > 10, soany()isTrue. Every quantity is at least 1, soall()isTrue.q > 1isTruefor 2 and 25, so the sum is 2.any()of nothing isFalse: no value is truthy.all()of nothing isTrue: no value breaks the rule. This is vacuous truth. A quality gate built onall()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”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.
Beauty: 25 units, revenue 702.29 USDLines with more than 1 unit: 14with 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 valuesHint 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) == 14assert beauty_units >= 14Beauty: 25 units, revenue 702.29 USDLines with more than 1 unit: 14How it works:
- Each
sum()filters the rows with its ownifclause, so no list of Beauty rows is built. - Each
sum()consumes a generator expression, so no list of numbers is built. int(row["quantity"]) > 1is a boolean, and the sum counts theTruevalues.
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.
M13-W06 · Unpack a log line
Section titled “M13-W06 · Unpack a log line”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.
INFO GET /api/v1/reports/2024-04 -> 200 in 87msline = ( "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"]INFO GET /api/v1/reports/2024-04 -> 200 in 87msHow it works:
- The two string literals in parentheses join into one string. This keeps the line under 88 characters.
split()with no argument splits on any run of whitespace.- Nine names take the first nine parts.
*restcollects whatever is left, here one item. If a line had fewer than nine parts, unpacking would raise aValueErrorat 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”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.
Warnings: 1WARN = "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 = 0for line in lines: *_, status = line.split(",") if status is WARN: # TODO: fix this comparison warnings += 1print(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 = 0for line in lines: *_, status = line.split(",") if status == WARN: warnings += 1print(f"Warnings: {warnings}")assert warnings == 1Warnings: 1How it works:
split(",")creates new string objects. The last part is equal to"warn", but it is not the same object asWARN, sostatus is WARNisFalse.==compares the values, which is what the task needs.*_, statuskeeps 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”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.
20.58Nonedef 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 stylereadings = [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 None20.58NoneHow it works:
meanissnake_caseandvaluessays what the parameter holds.Lis a one-letter name that says nothing about its content, and an uppercase name for a variable breaks thesnake_caserule. (PEP 8 forbidsl,OandIas names, because in many fonts they look like1and0.)if not values:coversNoneand[]in one test.sum(values)replaces the index loop and the accumulator.- 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”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.
S1: 10 values, min 1.7, max 2.67S2: 10 values, min 2.15, max 3.39S3: 10 values, min 1.65, max 2.5S4: 10 values, min 2.17, max 3.83with 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 orderHint 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()) == 40S1: 10 values, min 1.7, max 2.67S2: 10 values, min 2.15, max 3.39S3: 10 values, min 1.65, max 2.5S4: 10 values, min 2.17, max 3.83How it works:
list(...)[:40]reads the file and keeps the first 40 rows. The file is small, so reading it all is fine.- 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. setdefault()returns the list for the sensor, creating it the first time, andappend()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”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.
['O002118: quantity 999'][]['O002118: quantity 999', 'O007568: quantity -3']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 collectsHint 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['O002118: quantity 999'][]['O002118: quantity 999', 'O007568: quantity -3']How it works:
Noneis immutable, so aNonedefault is safe. The function creates a new list on each call that does not pass one.- A caller who passes
collectedgets the problems of several lines in one list. That is the job the parameter was for. - The constant
MAX_QUANTITYreplaces the magic number 50. It matchesthresholds.max_quantityindata/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”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.
tenure_months: 1.000monthly_charges: 0.492logins_last_30d: 0.283ranges = { "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 itHint 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.0assert all(0 <= v <= 1 for v in scaled.values())tenure_months: 1.000monthly_charges: 0.492logins_last_30d: 0.283How it works:
- In the starter, all three lambdas share the comprehension’s
lowandhigh. When they run, these hold(0, 60), so the tenure 72 becomes 72 / 60 = 1.2. - Each call of
make_scaler()creates a new scope with its ownlowandhigh, andscaleremembers that scope. - 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”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.
kept: [22.3, 22.41, 22.5, 22.38]spikes: [38.03, 37.2]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 insteadHint 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.0temps = [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_Ckept: [22.3, 22.41, 22.5, 22.38]spikes: [38.03, 37.2]How it works:
- The original list stays unchanged, so you can still compare before and after.
- The two comprehensions use opposite conditions, so every reading lands in exactly one list. The first assert checks it.
- 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)[22.3, 22.41, 22.5, 22.38] [38.03, 37.2]M13-C05 · Parse readings.txt with EAFP
Section titled “M13-C05 · Parse readings.txt with EAFP”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.
40 valid readings, mean 21.06Bad lines: [(12, 'error'), (24, ''), (35, 'n/a')]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 linesHint 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) == 43assert [n for n, _ in bad_lines] == [12, 24, 35]40 valid readings, mean 21.06Bad lines: [(12, 'error'), (24, ''), (35, 'n/a')]How it works:
float()ignores the trailing line break and raisesValueErrorforerror, the empty line andn/a.- The
elseclause runs only whenfloat()succeeded. It keeps theappend()out of thetry, so an error there would not be mistaken for a bad line. 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”Choose a method and justify it: for each task, choose LBYL, EAFP or dict.get(), write the function and give a one-sentence reason.
count_blank_lines(path): count the blank lines ofdata/readings.txt.parse_quantity(text): returnint(text), orNonefor text such as"three".phone_of(customer): the phone of a record indata/customers.json, or"no phone".row_count(path): the number of data rows of a monthly report, orNoneif the file does not exist.
1[3, None, 12]['+1-555-908-5284', 'no phone'][55, None]def count_blank_lines(path: Path) -> int: ... # TODOdef parse_quantity(text: str) -> int | None: ... # TODOdef phone_of(customer: dict[str, Any]) -> str: ... # TODOdef 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.csvHint 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 Noneassert row_count(Path("data/reports/2024-06.csv")) == 551[3, None, 12]['+1-555-908-5284', 'no phone'][55, None]How it works:
- Blank lines (LBYL). The test
not line.strip()is the definition of a blank line, so the check cannot drift from the operation. - Quantity (EAFP).
int()accepts spaces, a sign and underscores. An LBYL check such astext.isdigit()would reject" 12 ". - Phone (
get).customer.get("phone")returnsNonefor a missing key and for anullvalue;orreplaces both. - 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”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.
2024-01: 14162.33 ==: True isclose: True2024-02: 4719.039999999997 ==: False isclose: True2024-03: 12296.719999999994 ==: False isclose: True2024-04: 10879.039999999992 ==: False isclose: True2024-05: 6675.859999999994 ==: False isclose: True2024-06: 8533.399999999992 ==: False isclose: Truelisted = { "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()) == 12024-01: 14162.33 ==: True isclose: True2024-02: 4719.039999999997 ==: False isclose: True2024-03: 12296.719999999994 ==: False isclose: True2024-04: 10879.039999999992 ==: False isclose: True2024-05: 6675.859999999994 ==: False isclose: True2024-06: 8533.399999999992 ==: False isclose: TrueHow it works:
- 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. - 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.
math.isclose()accepts a relative difference of1e-09, about 0.00001 USD on 10,000 USD. All six months pass.- A pipeline should use
math.isclose(), or compare rounded cents:round(total, 2) == listed[...]. For a ledger that must be exact, sumDecimalvalues.
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.
M13-C08 · Price an order with Decimal
Section titled “M13-C08 · Price an order with Decimal”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.
Fitness Tracker exact 179.982 Decimal 179.98 float 179.98Adjustable Dumbbells exact 251.100 Decimal 251.10 float 251.1Electric Toothbrush exact 269.955 Decimal 269.96 float 269.95 <- differsOrder total: 701.04CENT = 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 totalHint 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 = 0for 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 == 1Fitness Tracker exact 179.982 Decimal 179.98 float 179.98Adjustable Dumbbells exact 251.100 Decimal 251.10 float 251.1Electric Toothbrush exact 269.955 Decimal 269.96 float 269.95 <- differsOrder total: 701.04How it works:
Decimal(price) * qtyis exact, because both come from text and integers. Theexactcolumn shows the unrounded amounts.- 269.955 is exactly halfway.
ROUND_HALF_UProunds it to 269.96. The float product is stored as slightly less than 269.955, soround()gives 269.95. - 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”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).
{'2024-01': 48, '2024-02': 48, '2024-03': 47, '2024-04': 52, '2024-05': 47, '2024-06': 55}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 pathlibHint 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{'2024-01': 48, '2024-02': 48, '2024-03': 47, '2024-04': 52, '2024-05': 47, '2024-06': 55}How it works:
glob("*.csv")replaceslistdir()plus theendswith()filter.withcloses each file, even if a read fails.open()with nowithleaks the file handle on an error.path.stemreplacesname.replace(".csv", ""), which would also damage a name such assales.csv_backup.csv.sorted()gives a fixed order. The two dicts compare equal in any order, but the printed output must be stable.- The solution block is marked
nolintonly 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”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.
All ids start with C: TrueSome total_charges are blank: TrueCustomers with 60+ months: 401with Path("data/customers.csv").open(newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f))
ids_ok = Truefor r in rows: if not r["customer_id"].startswith("C"): ids_ok = False breakhas_blank_total = Falsefor r in rows: if r["total_charges"] == "": has_blank_total = Truelong_tenure = 0for 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_totalAll ids start with C: TrueSome total_charges are blank: TrueCustomers with 60+ months: 401How it works:
all()stops at the first id that fails, like thebreakin the original.any()stops at the first blank. The original loop kept reading all 5,000 rows after it found one.sum()of booleans counts theTruevalues.- The data dictionary says that 10 brand-new customers have a blank
total_charges, sohas_blank_totalisTrue.
Alternative: Counter(int(r["tenure_months"]) >= 60 for r in rows)[True] also counts, but sum() says it more directly.
M13-C11 · Fix the ruff findings by hand
Section titled “M13-C11 · Fix the ruff findings by hand”The script orders_messy.py counts the orders of 100 USD or more per customer in data/customers.json. It runs correctly:
import json, osfrom 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))Customers with big orders: 15Most big orders: C00003Ruff reports these findings with the module configuration:
ruff check --output-format concise orders_messy.pyorders_messy.py:1:1: E401 [*] Multiple imports on one lineorders_messy.py:1:1: I001 [*] Import block is un-sorted or un-formattedorders_messy.py:6:9: PTH123 `open()` should be replaced by `Path.open()`orders_messy.py:6:9: SIM115 Use a context manager for opening filesorders_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 annotationsorders_messy.py:24:27: PTH118 `os.path.join()` should be replaced by `Path` with `/` operatororders_messy.py:25:7: UP031 Use format specifiers instead of percent formatorders_messy.py:26:7: UP031 Use format specifiers instead of percent formatFound 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.
Customers with big orders: 15Most big orders: C00003# 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 Noneassert counts[top_customer(counts)] == max(counts.values())Customers with big orders: 15Most big orders: C00003How it works:
E401,I001: the imports are gone from the solution, because the page setup importsjsonandPath. In your own script, writeimport jsonandfrom pathlib import Pathon two lines.PTH123,SIM115,PTH118:Path("data") / "customers.json"andread_text()replaceos.path.join(),open()andclose().E711,E701: the== Nonetest was never needed, so it is gone instead of fixed.UP045,UP031:str | Noneand f-strings.- Not a ruff rule:
candobecamecustomerandorder, andBIG_ORDER_USDnames 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”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.
{'C00003': ['O001975'], 'C00004': ['O007106']}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 comprehensionHint 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"])}{'C00003': ['O001975'], 'C00004': ['O007106']}How it works:
- Each helper has one job, a name that says what it selects and a docstring. A reviewer can check each rule on its own.
"vip" in customer["tags"]replaces theany()with a membership test.- The final comprehension has one
forand oneif, and it reads like the task: “for each premium vip customer, their big multi-item orders”. - 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”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.
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 itHint 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]['vip', 'new'][2, 2, 2]True FalseFalse True[-999, 21]How it works:
- Mutable default. Both calls share one list, so it holds
vipandnew. Fix:tags=None. - Late binding. The three lambdas share
n, which is 2 after the comprehension. Fix:lambda n=n: n. - Identity.
join()builds a new string. It is equal to"no-data", not the same object. Fix:==. - Float precision.
0.1 * 3is0.30000000000000004. Fix:math.isclose(). - Changing a list during a loop. The loop sees
-999at position 0 and removes it. At position 1 it sees another-999and callsremove(), which deletes the first-999in 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.
Challenge
Section titled “Challenge”M13-X01 · Parse a gateway batch file end to end
Section titled “M13-X01 · Parse a gateway batch file end to end”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.
S1: kept 5, dropped 1, corrupt 0, mean 20.29 CS2: kept 4, dropped 2, corrupt 0, mean 26.28 CS3: kept 2, dropped 0, corrupt 1, mean 19.25 CS4: kept 2, dropped 1, corrupt 0, mean 24.37 CStatuses: {'ok': 4, 'warn': 1, 'fail': 1}Sensors with warn or fail: ['S2', 'S4']MISSING = -999.0batch = [ "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 failHint 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.0ALERT_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()) == 4assert corrupt_by_sensor["S3"] == 1assert sorted(alerted) == ["S2", "S4"]S1: kept 5, dropped 1, corrupt 0, mean 20.29 CS2: kept 4, dropped 2, corrupt 0, mean 26.28 CS3: kept 2, dropped 0, corrupt 1, mean 19.25 CS4: kept 2, dropped 1, corrupt 0, mean 24.37 CStatuses: {'ok': 4, 'warn': 1, 'fail': 1}Sensors with warn or fail: ['S2', 'S4']How it works:
parse_line()keepsfloat()alone in thetry. A corrupt value is counted and skipped withcontinue. The-999.0check comes after the parse, as a plain LBYL business rule.- The function never removes from a list. It sorts each value into the right bucket on the first pass.
- The function returns counts instead of filling a shared list, so it has no mutable default and no hidden state.
- Implicit concatenation of two f-strings keeps the long
print()under 88 characters. - 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”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.
basic: 7 customers, 21 orders, revenue 5629.30, 0 without orderspremium: 6 customers, 14 orders, revenue 4187.06, 1 without ordersstandard: 7 customers, 13 orders, revenue 3895.34, 2 without ordersChanged 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 ordersdef 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 linesHint 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) == expectedprint("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) != expectedbasic: 7 customers, 21 orders, revenue 5629.30, 0 without orderspremium: 6 customers, 14 orders, revenue 4187.06, 1 without ordersstandard: 7 customers, 13 orders, revenue 3895.34, 2 without ordersChanged 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 ordersHow it works:
- Four named collections replace the list
[0, 0, 0.0, 0].orders[plan]says whatplans[p][1]only implied. sum(o["amount"] for o in c["orders"])replaces the inner loop. For an empty list it is 0.without_orders[plan] += not c["orders"]addsTrue(1) for an empty list andFalse(0) otherwise.plan_totals()does the counting once, and the two report functions only format. That split makes the v2 change small.- 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.
- The summing differs: the legacy code adds each order to the plan total, while
plan_totals()first sums each customer’s orders withsum()(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 withmath.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”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.
quantity < min_quantity (1): 6 violations, 0 unparsablequantity > max_quantity (50): 4 violations, 0 unparsablediscount > max_discount (0.2): 0 violations, 24 unparsableRows breaking any rule: 10 of 1200import 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 ruleHint 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 operatorfrom 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"] == 0max_check = checks["quantity > max_quantity"][1]assert max_check(51) and not max_check(50)quantity < min_quantity (1): 6 violations, 0 unparsablequantity > max_quantity (50): 4 violations, 0 unparsablediscount > max_discount (0.2): 0 violations, 24 unparsableRows breaking any rule: 10 of 1200How it works:
make_check()creates a new scope for each rule, so eachcheckremembers its owncompareandlimit. The last assert tests the boundary of one rule: 51 breaks it, 50 does not.parse_number()uses LBYL for the known missing tokens (an exact, cheap test from the config) and EAFP for everything else.- 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.
breaks_any_rule()parses each value once, thenany()stops at the first broken rule. A missing value breaks no rule, because theNonetest comes first andandshort-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”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.
Lines checked: 20228, differ from half up: 116Differences: [Decimal('-0.01')]Net difference: -1.16Top products: Shampoo and Conditioner Set: 52 lines Merino Wool Sweater: 45 lines Chef's Knife Set: 16 linesDiffer from half even: 2from 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_EVENHint 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)Lines checked: 20228, differ from half up: 116Differences: [Decimal('-0.01')]Net difference: -1.16Top products: Shampoo and Conditioner Set: 52 lines Merino Wool Sweater: 45 lines Chef's Knife Set: 16 linesDiffer from half even: 2How it works:
expected_amount()computes the exact line amount from the text, then rounds it with the rule it receives.Decimalmakes the comparison exact: no tolerance is needed.- The list comprehension with
if dkeeps only the non-zero differences, becauseDecimal("0")is falsy. - Every difference is exactly one cent down: the file rounded those halfway amounts down.
- 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”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.
S1: n=3 ok=1 alerts=0 mean=20.40 calibrated=TrueS2: n=3 ok=1 alerts=1 mean=22.87 calibrated=FalseS1: n=3 ok=1 alerts=2 mean=21.30 calibrated=FalseS2: n=2 ok=0 alerts=2 mean=24.00 calibrated=FalseSENTINEL = -999.0OK = "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 gotchasHint 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 Callablefrom typing import TypedDict
SENTINEL = -999.0OK = "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 callsassert report_1[0].endswith("calibrated=True")assert report_2[1] == "S2: n=2 ok=0 alerts=2 mean=24.00 calibrated=False"S1: n=3 ok=1 alerts=0 mean=20.40 calibrated=TrueS2: n=3 ok=1 alerts=1 mean=22.87 calibrated=FalseS1: n=3 ok=1 alerts=2 mean=21.30 calibrated=FalseS2: n=2 ok=0 alerts=2 mean=24.00 calibrated=FalseHow it works:
- 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. - Late binding. All alert lambdas compared with the last limit, 23.0.
make_alert()gives each sensor its own limit. - Identity.
status is OKwasFalsefor a status fromsplit(), sookstayed 0.==counts the ok batches. - List changed during iteration.
clean()skipped the second of two adjacent-999.0codes, which then went into the mean. The comprehension removes all of them. - Float equality. The mean of 20.0, 20.4 and 20.8 is
20.400000000000002, so== 20.4wasFalse.math.isclose()accepts it. - 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.