Skip to content

09. Standard library power tools — Exercises

These exercises practice every tool of the standard library lesson. Most of them read the course datasets: data/sales.csv, data/sensors.csv, data/customers.csv, data/logs/app.log, data/reports/ and data/config.json.

How to work:

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

Each solution is self-contained: it has its own imports and ends with assert checks. Exercises that write files write them into an output/ folder, never into data/.

Warm-up

The first 12 lines of data/sales.csv have these categories. Count them with a Counter. Print the three most common categories with their counts, then the count of "Sports".

Expected output
Clothing 5
Home 2
Electronics 2
Sports: 0
Starter
categories = [
"Home", "Clothing", "Clothing", "Clothing", "Electronics", "Books",
"Home", "Electronics", "Beauty", "Clothing", "Books", "Clothing",
]
# TODO: count the categories with collections.Counter
# TODO: print the 3 most common, then the count of "Sports"
Hint 1

Counter(categories) counts every item of the list. most_common(3) returns a list of (category, count) tuples.

Hint 2

A missing key in a Counter gives 0. When two counts tie, most_common() keeps the order in which the items first appeared.

Solution
from collections import Counter
categories = [
"Home", "Clothing", "Clothing", "Clothing", "Electronics", "Books",
"Home", "Electronics", "Beauty", "Clothing", "Books", "Clothing",
]
counts = Counter(categories)
for category, count in counts.most_common(3):
print(category, count)
print("Sports:", counts["Sports"])
assert counts.total() == len(categories)
assert counts["Clothing"] == 5
assert counts["Sports"] == 0
Output
Clothing 5
Home 2
Electronics 2
Sports: 0

How it works:

  1. Counter(categories) walks the list once and adds 1 per item.
  2. most_common(3) sorts by count. Home, Electronics and Books all have 2. Ties keep first-appearance order, and Electronics appears before Books, so it takes the third place.
  3. counts["Sports"] returns 0 for the missing key instead of raising KeyError.
  4. total() adds all counts, which must equal the number of lines.

Alternative: a plain dict with get(): counts[c] = counts.get(c, 0) + 1 in a loop, then sorted(counts.items(), key=lambda kv: kv[1], reverse=True)[:3]. It works, but it takes four lines for what Counter does in one.

Warm-up

These are the first 12 rows of data/sensors.csv as (sensor_id, temperature_c) pairs. Group the temperatures by sensor with a defaultdict(list). Print each sensor, its list and its mean, rounded to 2 decimals.

Expected output
S1 [20.21, 20.22, 20.16] 20.2
S2 [22.3, 22.44, 22.25] 22.33
S3 [19.4, 19.46, 19.54] 19.47
S4 [24.52, 24.63, 24.73] 24.63
Starter
rows = [
("S1", 20.21), ("S2", 22.3), ("S3", 19.4), ("S4", 24.52),
("S1", 20.22), ("S2", 22.44), ("S3", 19.46), ("S4", 24.63),
("S1", 20.16), ("S2", 22.25), ("S3", 19.54), ("S4", 24.73),
]
# TODO: group the temperatures by sensor with defaultdict(list)
# TODO: print each sensor, its temperatures and their mean
Hint 1

by_sensor = defaultdict(list) creates an empty list the first time you use a new key. Unpack each pair in the loop: for sensor_id, temp in rows:.

Hint 2

by_sensor[sensor_id].append(temp) needs no if. statistics.mean(temps) gives the mean.

Solution
import statistics
from collections import defaultdict
rows = [
("S1", 20.21), ("S2", 22.3), ("S3", 19.4), ("S4", 24.52),
("S1", 20.22), ("S2", 22.44), ("S3", 19.46), ("S4", 24.63),
("S1", 20.16), ("S2", 22.25), ("S3", 19.54), ("S4", 24.73),
]
by_sensor = defaultdict(list)
for sensor_id, temp in rows:
by_sensor[sensor_id].append(temp)
for sensor_id, temps in by_sensor.items():
print(sensor_id, temps, round(statistics.mean(temps), 2))
assert len(by_sensor) == 4
assert by_sensor["S3"] == [19.4, 19.46, 19.54]
Output
S1 [20.21, 20.22, 20.16] 20.2
S2 [22.3, 22.44, 22.25] 22.33
S3 [19.4, 19.46, 19.54] 19.47
S4 [24.52, 24.63, 24.73] 24.63

How it works:

  1. The default factory list makes [] for each new sensor id.
  2. append() adds each temperature to its sensor’s list, in file order.
  3. A defaultdict keeps insertion order like a dict, so the sensors print in the order they first appeared.

Alternative: dict.setdefault() does the same with a plain dict: by_sensor.setdefault(sensor_id, []).append(temp). It builds a new empty list on every call, even when the key exists, so defaultdict is cleaner in a loop.

M09-W03 · Predict the output: a bounded deque

Section titled “M09-W03 · Predict the output: a bounded deque”
Warm-up

Predict the output: write down what each print() shows. Then run the code and compare.

Acceptance criteria:

  • Write your prediction for both lines before you run the code.
  • Run the code. Your prediction matches the Output in the solution.
  • You can explain which value fell out at each step.
Starter
from collections import deque
window = deque([1, 2], maxlen=3)
window.append(3)
window.append(4)
window.appendleft(0)
print(list(window))
print(window.maxlen, len(window))
# TODO: write your prediction for each line before you run it
Hint 1

A full deque with maxlen drops an item from the other end when you add one.

Hint 2

Which item does append(4) push out? And which end loses an item when appendleft() adds on the left?

Solution
from collections import deque
window = deque([1, 2], maxlen=3)
window.append(3)
window.append(4)
window.appendleft(0)
print(list(window))
print(window.maxlen, len(window))
assert list(window) == [0, 2, 3]
Output
[0, 2, 3]
3 3

How it works:

  1. The deque starts as [1, 2], with room for one more.
  2. append(3) fills it: [1, 2, 3].
  3. append(4) adds on the right, so the leftmost item, 1, falls out: [2, 3, 4].
  4. appendleft(0) adds on the left, so the rightmost item, 4, falls out: [0, 2, 3].
  5. maxlen stays 3, and a full deque has length 3.

Alternative: in a rolling window, always add on one side (append) and let the other side drop. Mixing append and appendleft on a bounded deque is legal but hard to read.

Warm-up

Turn three lines of data/stores.csv into Store named tuples with the fields store_id, city, region, size_sqm (an int) and opened. Print the city and size of the largest store. Then the store is extended to 3,600 m²: print the updated record, and show that the original record did not change.

Expected output
New York 3400
Store(store_id='S07', city='New York', region='East', size_sqm=3600, opened='2008-02-23')
original: 3400
Starter
from collections import namedtuple
lines = [
"S01,Chicago,North,2850,2009-03-14",
"S02,Minneapolis,North,1950,2012-08-01",
"S07,New York,East,3400,2008-02-23",
]
# TODO: define Store with namedtuple
# TODO: build one Store per line, with size_sqm as an int
# TODO: find the largest store, print it, then print an updated copy
Hint 1

Store = namedtuple("Store", ["store_id", "city", "region", "size_sqm", "opened"]). Split each line with split(",") and unpack the five parts.

Hint 2

max(stores, key=attrgetter("size_sqm")) finds the largest store (from operator import attrgetter). _replace(size_sqm=3600) returns a new record.

Solution
from collections import namedtuple
from operator import attrgetter
Store = namedtuple("Store", ["store_id", "city", "region", "size_sqm", "opened"])
lines = [
"S01,Chicago,North,2850,2009-03-14",
"S02,Minneapolis,North,1950,2012-08-01",
"S07,New York,East,3400,2008-02-23",
]
stores = []
for text in lines:
store_id, city, region, size, opened = text.split(",")
stores.append(Store(store_id, city, region, int(size), opened))
largest = max(stores, key=attrgetter("size_sqm"))
print(largest.city, largest.size_sqm)
extended = largest._replace(size_sqm=3600)
print(extended)
print("original:", largest.size_sqm)
assert extended.size_sqm == 3600 and largest.size_sqm == 3400
assert extended.store_id == "S07"
Output
New York 3400
Store(store_id='S07', city='New York', region='East', size_sqm=3600, opened='2008-02-23')
original: 3400

How it works:

  1. namedtuple builds the Store type with five named fields.
  2. Each line is split into five strings. Only the size needs a conversion.
  3. attrgetter("size_sqm") is a key function that reads .size_sqm, so max compares the sizes.
  4. Named tuples are immutable. _replace() builds a new record and leaves largest as it was.

Alternative: lambda s: s.size_sqm works as the key too. To build a record from a list of fields, use Store._make(fields), but then size_sqm stays a string unless you convert it first.

M09-W05 · Fix the bug: groupby counts are wrong

Section titled “M09-W05 · Fix the bug: groupby counts are wrong”
Warm-up

Fix the bug: this code should count the order lines per region, but every count is 1. Find out why and fix it with one change. The output must list the regions in alphabetical order.

Expected output
{'East': 1, 'North': 2, 'South': 2, 'West': 3}
Starter
from itertools import groupby
regions = ["West", "West", "South", "North", "West", "South", "East", "North"]
counts = {region: len(list(group)) for region, group in groupby(regions)}
print(counts) # {'West': 1, 'South': 1, 'North': 1, 'East': 1}
# TODO: fix the bug
Hint 1

groupby groups only consecutive equal items. How many separate runs of "West" does the list have?

Hint 2

The dict comprehension keeps the last run of each region, and the last run of West has length 1. Put equal regions next to each other first.

Solution
from itertools import groupby
regions = ["West", "West", "South", "North", "West", "South", "East", "North"]
counts = {region: len(list(group)) for region, group in groupby(sorted(regions))}
print(counts)
assert counts == {"East": 1, "North": 2, "South": 2, "West": 3}
assert sum(counts.values()) == len(regions)
Output
{'East': 1, 'North': 2, 'South': 2, 'West': 3}

How it works:

  1. Unsorted, groupby yields seven runs: West (2), South, North, West, South, East, North. Several keys repeat.
  2. The dict comprehension overwrites a key each time it repeats, so only the last run of each region survives. The last West run has length 1.
  3. sorted(regions) puts equal regions next to each other, so each region forms exactly one run. Sorting also gives the alphabetical order.

Alternative: dict(sorted(Counter(regions).items())) gives the same result without sorting the data, and it is the better tool for plain counting. Use groupby when you need the items of each group, or when runs are the point.

Warm-up

These are the units sold on each of the first 7 days of 2023 in data/sales.csv. Print the running total with itertools.accumulate. Then print the first day on which the running total reaches 100 units.

Expected output
[31, 50, 76, 106, 128, 155, 209]
100 units reached on 2023-01-04
Starter
days = [f"2023-01-0{n}" for n in range(1, 8)]
units = [31, 19, 26, 30, 22, 27, 54]
# TODO: compute the running total with accumulate
# TODO: print the first day on which it reaches 100
Hint 1

list(accumulate(units)) gives one running total per day.

Hint 2

Loop over zip(days, running) and break at the first total that is at least 100.

Solution
from itertools import accumulate
days = [f"2023-01-0{n}" for n in range(1, 8)]
units = [31, 19, 26, 30, 22, 27, 54]
running = list(accumulate(units))
print(running)
for day, total in zip(days, running):
if total >= 100:
print("100 units reached on", day)
break
assert running[-1] == sum(units)
assert day == "2023-01-04"
Output
[31, 50, 76, 106, 128, 155, 209]
100 units reached on 2023-01-04

How it works:

  1. accumulate() adds each value to the sum of the values before it: 31, 31 + 19 = 50, and so on.
  2. The last running total equals sum(units), which the first assert checks.
  3. zip() pairs each day with its running total. The loop stops at the first total of 100 or more: 106 on January 4.

Alternative: next(day for day, total in zip(days, running) if total >= 100) finds the same day in one expression. Module 10 explains next() and generator expressions.

M09-W07 · Predict the output: dates and durations

Section titled “M09-W07 · Predict the output: dates and durations”
Warm-up

Predict the output: write down what each line prints. Pay attention to leap years and to how a timedelta is shown.

Acceptance criteria:

  • Write your prediction for all five lines before you run the code.
  • Run the code. Your prediction matches the Output in the solution.
  • For each line you got wrong, you can name the rule that explains it.
Starter
from datetime import date, datetime, timedelta
print(date(2024, 2, 28) + timedelta(days=2))
print((date(2024, 12, 31) - date(2024, 1, 1)).days)
print((datetime(2024, 5, 1, 23, 50) + timedelta(minutes=20)).isoformat())
print(timedelta(hours=36))
print(timedelta(hours=36).days, timedelta(hours=36).seconds)
# TODO: write your prediction for each line before you run it
Hint 1

2024 is a leap year, so February has 29 days.

Hint 2

A timedelta stores whole days plus the seconds left over. .seconds is only the leftover part, not the total.

Solution
from datetime import date, datetime, timedelta
print(date(2024, 2, 28) + timedelta(days=2))
print((date(2024, 12, 31) - date(2024, 1, 1)).days)
print((datetime(2024, 5, 1, 23, 50) + timedelta(minutes=20)).isoformat())
print(timedelta(hours=36))
print(timedelta(hours=36).days, timedelta(hours=36).seconds)
assert timedelta(hours=36).total_seconds() == 129600
Output
2024-03-01
365
2024-05-02T00:10:00
1 day, 12:00:00
1 43200

How it works:

  1. February 28 plus 2 days is February 29, then March 1, because 2024 is a leap year.
  2. The difference between the first and the last day of a leap year is 365 days. The year has 366 days, but a difference counts the gaps between them.
  3. 23:50 plus 20 minutes rolls over midnight into May 2.
  4. 36 hours is shown as 1 day, 12:00:00.
  5. .days is 1 and .seconds is 43,200 (12 hours). For the whole duration in seconds, use total_seconds(): 129,600.

Alternative: check a date in the REPL before you trust it in a script. date(2024, 2, 29) works, and date(2023, 2, 29) raises ValueError: day is out of range for month.

M09-W08 · Find order ids in a support email

Section titled “M09-W08 · Find order ids in a support email”
Warm-up

A support email mentions order ids (O and 6 digits) and product ids (P and 3 digits). Extract them with re.findall. Print the order ids in the order they appear, then the sorted unique order and product ids. PO1234 and O45 are not valid ids.

Expected output
['O004512', 'O004519', 'O004512']
['O004512', 'O004519'] ['P003']
Starter
import re
email = (
"Hi team, order O004512 had a broken P003 TV. Order O004519 is fine. "
"Please refund O004512 and send a new P003. Ref: PO1234, O45."
)
# TODO: find all order ids and all product ids
# TODO: print the order ids, then the unique sorted ids
Hint 1

r"O\d{6}" matches an O followed by exactly six digits. Always write the pattern as a raw string.

Hint 2

\b marks a word boundary: the position between a word character and a non-word character. Put one before the letter so that PO1234 cannot match from its middle, and one after the digits so that a longer number cannot match its first digits.

Solution
import re
email = (
"Hi team, order O004512 had a broken P003 TV. Order O004519 is fine. "
"Please refund O004512 and send a new P003. Ref: PO1234, O45."
)
orders = re.findall(r"\bO\d{6}\b", email)
products = re.findall(r"\bP\d{3}\b", email)
print(orders)
print(sorted(set(orders)), sorted(set(products)))
assert len(orders) == 3 and "O45" not in orders
assert products == ["P003", "P003"]
Output
['O004512', 'O004519', 'O004512']
['O004512', 'O004519'] ['P003']

How it works:

  1. findall returns every non-overlapping match as a string, from left to right. O004512 appears twice.
  2. \b before O and P requires a word boundary. In PO1234, P is followed by O, which is not a digit, and O1234 has only 4 digits.
  3. set() removes the repeats and sorted() gives a stable order.

Alternative: one pattern finds both kinds of id: re.findall(r"\b[OP]\d+\b", email). Then check the length of each id. Two precise patterns are easier to read.

M09-W09 · Choose and justify: mean or median order value

Section titled “M09-W09 · Choose and justify: mean or median order value”
Warm-up

Choose and justify: these are the revenues of the 15 order lines of 2023-01-02 in data/sales.csv. A manager asks for “the typical line value”. Compute the mean, the median and the sample standard deviation with statistics. Print them, then print which one you would report and why, in one line.

Expected output
mean 106.26, median 79.99, stdev 109.13
Report the median: a few expensive lines pull the mean far above most lines.
Starter
import statistics
revenues = [86.0, 15.99, 279.0, 189.99, 26.99, 16.99, 246.98, 23.99,
34.99, 24.5, 79.99, 15.99, 349.0, 79.99, 123.49]
# TODO: compute mean, median and stdev
# TODO: print them and your choice
Hint 1

statistics.mean(), statistics.median() and statistics.stdev() each take the list.

Hint 2

A few large values pull the mean up. The median is the middle value of the sorted list, so large values do not move it.

Solution
import statistics
revenues = [86.0, 15.99, 279.0, 189.99, 26.99, 16.99, 246.98, 23.99,
34.99, 24.5, 79.99, 15.99, 349.0, 79.99, 123.49]
mean = statistics.mean(revenues)
median = statistics.median(revenues)
spread = statistics.stdev(revenues)
print(f"mean {mean:.2f}, median {median:.2f}, stdev {spread:.2f}")
print("Report the median: a few expensive lines pull the mean far above most lines.")
assert median < mean
assert sum(r < mean for r in revenues) > len(revenues) / 2
Output
mean 106.26, median 79.99, stdev 109.13
Report the median: a few expensive lines pull the mean far above most lines.

How it works:

  1. The mean is 106.26 USD, but 10 of the 15 lines are below it.
  2. The median is the 8th of the 15 sorted values: 79.99 USD, a common line value (Wireless Earbuds).
  3. The standard deviation (109.13) is even larger than the mean, a sign of a skewed, spread-out distribution.
  4. The second assert proves the point: more than half the lines are below the mean.

Alternative: report both, with the count: “15 lines, median 79.99 USD, mean 106.26 USD”. The mean is still the right number to compute total revenue, because mean × count = total.

M09-C01 · Top products by revenue in 2024

Section titled “M09-C01 · Top products by revenue in 2024”
Core

Read data/sales.csv and add up the revenue of each product for the year 2024 in a Counter. Print the top 3 products with their revenue and their share of the 2024 total, then the share of the top 3 together.

Expected output
14-inch Ultrabook Laptop 341,310.45 17.5%
55-inch 4K Smart TV 301,303.05 15.4%
Robot Vacuum 132,580.44 6.8%
Top 3 share: 39.7%
Starter
import csv
from collections import Counter
revenue = Counter()
# TODO: read data/sales.csv with csv.DictReader
# TODO: for 2024 rows, add float(row["revenue"]) to revenue[row["product"]]
# TODO: print the top 3 with their share, then the top-3 share
Hint 1

row["order_date"].startswith("2024") selects 2024. A Counter can hold float values: revenue[name] += float(row["revenue"]).

Hint 2

revenue.total() is the 2024 total. Format a share with :.1% and money with :,.2f.

Solution
import csv
import math
from collections import Counter
revenue = Counter()
with open("data/sales.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["order_date"].startswith("2024"):
revenue[row["product"]] += float(row["revenue"])
total = revenue.total()
top3 = revenue.most_common(3)
for product, value in top3:
print(f"{product:<26}{value:>12,.2f}{value / total:>7.1%}")
print(f"Top 3 share: {sum(value for _, value in top3) / total:.1%}")
assert math.isclose(total, 1_950_934.24, abs_tol=0.5)
assert len(revenue) == 30
Output
14-inch Ultrabook Laptop 341,310.45 17.5%
55-inch 4K Smart TV 301,303.05 15.4%
Robot Vacuum 132,580.44 6.8%
Top 3 share: 39.7%

How it works:

  1. startswith("2024") keeps the 11,147 lines of 2024.
  2. Each line adds its revenue to its product’s entry. A Counter treats a missing key as 0, so += works on the first line too.
  3. most_common(3) sorts by value, and total() adds every value. The assert checks the total against the data dictionary.
  4. The two most expensive electronics products and the Robot Vacuum bring 39.7% of the year’s revenue.

Alternative: defaultdict(float) sums just as well. Then sort with sorted(revenue.items(), key=lambda kv: kv[1], reverse=True)[:3]. Counter saves you that line.

M09-C02 · Orders and customers per channel

Section titled “M09-C02 · Orders and customers per channel”
Core

For December 2024 in data/sales.csv, collect the distinct order ids and the distinct customer ids of each channel (store, online) with defaultdict(set). Print a table with the number of lines, orders and customers per channel, and the orders per customer.

Expected output
Channel Lines Orders Customers Per cust.
online 851 628 572 1.10
store 816 609 538 1.13
Starter
import csv
from collections import Counter, defaultdict
lines = Counter()
orders = defaultdict(set)
customers = defaultdict(set)
# TODO: fill the three structures for December 2024
# TODO: print the table, channels in alphabetical order
Hint 1

row["order_date"].startswith("2024-12") selects December. Add with orders[channel].add(row["order_id"]).

Hint 2

len(orders[channel]) counts distinct orders. Orders per customer is len(orders[c]) / len(customers[c]).

Solution
import csv
from collections import Counter, defaultdict
lines = Counter()
orders = defaultdict(set)
customers = defaultdict(set)
with open("data/sales.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["order_date"].startswith("2024-12"):
channel = row["channel"]
lines[channel] += 1
orders[channel].add(row["order_id"])
customers[channel].add(row["customer_id"])
print(f"{'Channel':<8}{'Lines':>7}{'Orders':>8}{'Customers':>11}{'Per cust.':>11}")
for channel in sorted(orders):
n_orders, n_customers = len(orders[channel]), len(customers[channel])
print(f"{channel:<8}{lines[channel]:>7}{n_orders:>8}{n_customers:>11}"
f"{n_orders / n_customers:>11.2f}")
assert all(lines[c] >= len(orders[c]) >= len(customers[c]) for c in orders)
Output
Channel Lines Orders Customers Per cust.
online 851 628 572 1.10
store 816 609 538 1.13

How it works:

  1. One pass over the file fills three structures: a Counter for lines and two defaultdict(set) for the ids.
  2. A set keeps each id once, so len() counts distinct orders and customers.
  3. The assert checks the natural order of the counts: an order has at least one line, and a customer has at least one order.
  4. Two f-strings next to each other inside print() join into one string, which keeps the line under 88 characters.

Alternative: collect (channel, order_id) tuples in one set and count them with Counter(channel for channel, _ in pairs). It saves a structure but is harder to read.

M09-C03 · Seven-day moving average of daily revenue

Section titled “M09-C03 · Seven-day moving average of daily revenue”
Core

Sum the revenue per day for December 2024 from data/sales.csv. Then compute the 7-day moving average with a deque(maxlen=7): the mean of each day and the six days before it. Print the number of days, the first moving average (the week ending December 7) and the highest one with the date it ends on.

Expected output
31 days, 25 full windows
First 7-day average: 10,910.12 USD
Highest: 11,742.35 USD in the week ending 2024-12-18
Starter
import csv
from collections import defaultdict, deque
daily = defaultdict(float)
# TODO: sum the revenue per day for 2024-12
window = deque(maxlen=7)
# TODO: walk the days in order, keep the last 7 totals, track the highest average
Hint 1

ISO dates sort correctly as text, so for day in sorted(daily): walks the days in order.

Hint 2

Only compute the average when len(window) == 7. Keep the best (day, average) pair in a variable that starts as None.

Solution
import csv
from collections import defaultdict, deque
daily = defaultdict(float)
with open("data/sales.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["order_date"].startswith("2024-12"):
daily[row["order_date"]] += float(row["revenue"])
window = deque(maxlen=7)
averages = {}
for day in sorted(daily):
window.append(daily[day])
if len(window) == 7:
averages[day] = sum(window) / 7
best_day = max(averages, key=averages.get)
print(len(daily), "days,", len(averages), "full windows")
print(f"First 7-day average: {averages['2024-12-07']:,.2f} USD")
print(f"Highest: {averages[best_day]:,.2f} USD in the week ending {best_day}")
assert len(averages) == len(daily) - 6
assert min(daily.values()) <= averages[best_day] <= max(daily.values())
Output
31 days, 25 full windows
First 7-day average: 10,910.12 USD
Highest: 11,742.35 USD in the week ending 2024-12-18

How it works:

  1. defaultdict(float) sums each day’s lines.
  2. The deque always holds the last 7 daily totals. When it is full, each append() drops the oldest day.
  3. A month of 31 days has 25 full windows: the first ends on day 7.
  4. The best week ends on December 18, in the busiest stretch of the holiday season before Christmas.
  5. A moving average lies between the smallest and largest daily value, which the second assert checks.

Alternative: pandas does this in one line: daily_series.rolling(7).mean() (module 25). The deque version streams: it needs only 7 values in memory, whatever the length of the data.

M09-C04 · Send churned customers to the CRM in batches

Section titled “M09-C04 · Send churned customers to the CRM in batches”
Core

The CRM accepts at most 250 customer ids per request. Collect the ids of churned customers (churned == "1") from data/customers.csv and cut them into batches with itertools.batched. Print the number of churned customers, the number of batches and the size of the last one. Before that, peek at the first 3 churned ids with islice, without reading the whole file.

Expected output
first: ['C00012', 'C00031', 'C00102']
963 churned customers
4 batches; sizes [250, 250, 250, 213]
Starter
import csv
from itertools import batched, islice
# TODO: peek at the first 3 churned ids with islice
# TODO: collect all churned ids, then batch them by 250
Hint 1

A generator expression is lazy: (row["customer_id"] for row in reader if row["churned"] == "1"). islice(that, 3) stops after 3 ids.

Hint 2

batches = list(batched(churned, 250)) gives tuples. len(batches[-1]) is the size of the last one.

Solution
import csv
from itertools import batched, islice
with open("data/customers.csv", encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
churned_ids = (row["customer_id"] for row in reader if row["churned"] == "1")
print("first:", list(islice(churned_ids, 3)))
with open("data/customers.csv", encoding="utf-8", newline="") as f:
churned = [row["customer_id"] for row in csv.DictReader(f) if row["churned"] == "1"]
batches = list(batched(churned, 250))
print(len(churned), "churned customers")
print(len(batches), "batches; sizes", [len(batch) for batch in batches])
assert sum(len(batch) for batch in batches) == len(churned) == 963
assert all(len(batch) <= 250 for batch in batches)
Output
first: ['C00012', 'C00031', 'C00102']
963 churned customers
4 batches; sizes [250, 250, 250, 213]

How it works:

  1. The generator expression reads rows only on request. islice(..., 3) asks for 3 matching ids, then stops; the rest of the file is never read.
  2. The second with reads the file again and builds the full list.
  3. batched(churned, 250) cuts the 963 ids into tuples of 250, 250, 250 and 213.
  4. The asserts check that no id is lost and that no batch is too large.

Alternative: before Python 3.12, people sliced by hand: [churned[i:i + 250] for i in range(0, len(churned), 250)]. That works only on a list. batched also works on a stream, such as rows straight from a file.

M09-C05 · Fix the bug: the second sum is zero

Section titled “M09-C05 · Fix the bug: the second sum is zero”
Core

Fix the bug: this code combines the six monthly reports in data/reports/ and should print the number of rows, the revenue and the mean revenue per row. It crashes with ZeroDivisionError: division by zero. Explain why and fix it.

Expected output
297 rows, revenue 57,266.39, mean 192.82
Starter
import csv
from itertools import chain
from pathlib import Path
def read_rows(path):
with open(path, encoding="utf-8", newline="") as f:
yield from csv.DictReader(f)
paths = sorted(Path("data/reports").glob("*.csv"))
rows = chain.from_iterable(read_rows(path) for path in paths)
total = sum(float(row["revenue"]) for row in rows)
count = sum(1 for row in rows)
print(f"{count} rows, revenue {total:,.2f}, mean {total / count:.2f}")
# TODO: fix the bug
Hint 1

Print count before the last line. What is it? What kind of object is rows?

Hint 2

chain returns an iterator. The first sum() used it up, so the second one sees no rows. Store the rows in a list, or compute both values in one loop.

Solution
import csv
from itertools import chain
from pathlib import Path
def read_rows(path):
with open(path, encoding="utf-8", newline="") as f:
yield from csv.DictReader(f)
paths = sorted(Path("data/reports").glob("*.csv"))
rows = list(chain.from_iterable(read_rows(path) for path in paths))
total = sum(float(row["revenue"]) for row in rows)
count = len(rows)
print(f"{count} rows, revenue {total:,.2f}, mean {total / count:.2f}")
assert count == 297
assert round(total, 2) == 57266.39
Output
297 rows, revenue 57,266.39, mean 192.82

How it works:

  1. In the buggy code, rows is an iterator. The first sum() pulled all 297 rows out of it.
  2. The second sum() found the iterator empty, so count was 0 and the division failed.
  3. list(...) stores the rows once. A list can be read as often as you like, and len() counts it directly.

Alternative: keep the stream and count in the same loop, which uses no memory for the rows:

import csv
from itertools import chain
from pathlib import Path
def read_rows(path):
with open(path, encoding="utf-8", newline="") as f:
yield from csv.DictReader(f)
paths = sorted(Path("data/reports").glob("*.csv"))
count, total = 0, 0.0
for row in chain.from_iterable(read_rows(path) for path in paths):
count += 1
total += float(row["revenue"])
print(count, round(total, 2))
Output
297 57266.39
Core

Sum the revenue per month (YYYY-MM) of data/sales.csv for 2024. Use itertools.pairwise to compute the change from each month to the next. Print the month with the biggest rise and the month with the biggest fall, with the percentage change.

Expected output
12 months, 11 changes
Biggest rise: 2024-11 +61.6%
Biggest fall: 2024-04 -21.1%
Starter
import csv
from collections import defaultdict
from itertools import pairwise
monthly = defaultdict(float)
# TODO: sum revenue per month for 2024
# TODO: compute (month, change) for each pair of months with pairwise
# TODO: print the biggest rise and the biggest fall
Hint 1

row["order_date"][:7] is the month. months = sorted(monthly) puts them in order.

Hint 2

For each before, after in pairwise(months), the change is (monthly[after] - monthly[before]) / monthly[before]. Use max and min with a key on the change.

Solution
import csv
from collections import defaultdict
from itertools import pairwise
from operator import itemgetter
monthly = defaultdict(float)
with open("data/sales.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["order_date"].startswith("2024"):
monthly[row["order_date"][:7]] += float(row["revenue"])
months = sorted(monthly)
changes = [
(after, (monthly[after] - monthly[before]) / monthly[before])
for before, after in pairwise(months)
]
rise = max(changes, key=itemgetter(1))
fall = min(changes, key=itemgetter(1))
print(len(months), "months,", len(changes), "changes")
print(f"Biggest rise: {rise[0]} {rise[1]:+.1%}")
print(f"Biggest fall: {fall[0]} {fall[1]:+.1%}")
assert len(changes) == 11
Output
12 months, 11 changes
Biggest rise: 2024-11 +61.6%
Biggest fall: 2024-04 -21.1%

How it works:

  1. A defaultdict(float) sums the lines of each month.
  2. pairwise(months) yields 11 pairs for 12 months: ("2024-01", "2024-02") and so on.
  3. Each change is stored with the later month, the month that rose or fell.
  4. itemgetter(1) picks the change from each tuple, so max and min compare the changes.
  5. November rises most (+61.6%): Black Friday and the start of the holiday season. The biggest fall is April (−21.1%). The dip after the holidays falls into January 2025, which is outside the data.

Alternative: zip(months, months[1:]) gives the same pairs on a list. pairwise also works on a stream and says what it means.

Core

Market basket analysis finds products that customers buy in the same order. Group the 2024 lines of data/sales.csv into baskets: one set of products per order_id. Count every pair of products in each basket with itertools.combinations and a Counter. Print the number of orders, how many have 2 or more products, and the 3 most frequent pairs.

Expected output
8156 orders, 2299 with 2+ products, 3683 pairs
32 Organic Cotton T-Shirt + Wireless Earbuds
30 Non-Slip Yoga Mat + Wireless Earbuds
24 Non-Slip Yoga Mat + Organic Cotton T-Shirt
Starter
import csv
from collections import Counter, defaultdict
from itertools import combinations
baskets = defaultdict(set)
# TODO: fill one set of products per 2024 order
pairs = Counter()
# TODO: count every pair of products in each basket
# TODO: print the counts and the top 3 pairs
Hint 1

baskets[row["order_id"]].add(row["product"]) builds the baskets. A basket with one product has no pairs.

Hint 2

Sort each basket before combinations(sorted(basket), 2). Then ("A", "B") and ("B", "A") are always counted as the same pair. pairs.update(...) counts many items at once.

Solution
import csv
from collections import Counter, defaultdict
from itertools import combinations
baskets = defaultdict(set)
with open("data/sales.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["order_date"].startswith("2024"):
baskets[row["order_id"]].add(row["product"])
pairs = Counter()
for basket in baskets.values():
pairs.update(combinations(sorted(basket), 2))
multi = sum(1 for basket in baskets.values() if len(basket) >= 2)
print(len(baskets), "orders,", multi, "with 2+ products,", pairs.total(), "pairs")
for (first, second), count in pairs.most_common(3):
print(f"{count:>3} {first} + {second}")
assert multi < len(baskets)
Output
8156 orders, 2299 with 2+ products, 3683 pairs
32 Organic Cotton T-Shirt + Wireless Earbuds
30 Non-Slip Yoga Mat + Wireless Earbuds
24 Non-Slip Yoga Mat + Organic Cotton T-Shirt

How it works:

  1. defaultdict(set) collects the products of each order. An order has 1 to 3 lines with distinct products.
  2. A basket of 2 products gives 1 pair, and a basket of 3 gives 3 pairs: combinations picks each unordered pair once.
  3. Sorting each basket first makes the pair order canonical, so the same two products always form the same tuple.
  4. pairs.update(iterable) adds 1 for each pair. The top pairs are cheap, popular products that appear in many orders.

Alternative: divide each pair count by the number of orders that contain the first product. That ratio, the confidence of “if A then B”, is how recommendation rules are ranked. pandas and the mlxtend package compute it at scale.

M09-C08 · Refactor: cache a slow cost lookup

Section titled “M09-C08 · Refactor: cache a slow cost lookup”
Core

Refactor: this script computes the gross profit (revenue − unit cost × quantity) of the first 2,000 lines of data/sales.csv. unit_cost() reads data/products.csv on every call, so the script reads that file 2,000 times. Add functools.cache so that each product is looked up only once. Print the profit, the number of file reads and the cache statistics.

Expected output
profit 175,022.46, file reads 26
CacheInfo(hits=1974, misses=26, maxsize=None, currsize=26)
Starter
import csv
from itertools import islice
file_reads = 0
def unit_cost(product_id):
global file_reads
file_reads += 1
with open("data/products.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["product_id"] == product_id:
return float(row["unit_cost"])
raise KeyError(product_id)
profit = 0.0
with open("data/sales.csv", encoding="utf-8", newline="") as f:
for row in islice(csv.DictReader(f), 2000):
cost = unit_cost(row["product_id"]) * int(row["quantity"])
profit += float(row["revenue"]) - cost
print(f"profit {profit:,.2f}, file reads {file_reads}") # file reads 2000
# TODO: cache unit_cost and print its cache_info()
Hint 1

Put @cache (from functools) on the line above def unit_cost. Nothing else in the loop changes.

Hint 2

A cached function counts as a hit when it returns a stored result. unit_cost.cache_info() shows hits, misses and the cache size. The misses equal the file reads.

Solution
import csv
from functools import cache
from itertools import islice
file_reads = 0
@cache
def unit_cost(product_id):
global file_reads
file_reads += 1
with open("data/products.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["product_id"] == product_id:
return float(row["unit_cost"])
raise KeyError(product_id)
profit = 0.0
with open("data/sales.csv", encoding="utf-8", newline="") as f:
for row in islice(csv.DictReader(f), 2000):
cost = unit_cost(row["product_id"]) * int(row["quantity"])
profit += float(row["revenue"]) - cost
print(f"profit {profit:,.2f}, file reads {file_reads}")
print(unit_cost.cache_info())
info = unit_cost.cache_info()
assert info.hits + info.misses == 2000
assert file_reads == info.misses == info.currsize
Output
profit 175,022.46, file reads 26
CacheInfo(hits=1974, misses=26, maxsize=None, currsize=26)

How it works:

  1. @cache stores each result under its argument, the product id.
  2. The first call for a product is a miss: it reads the file. Every later call for the same product is a hit and reads nothing.
  3. The first 2,000 lines contain 26 distinct products, so the file is read 26 times instead of 2,000. The profit is the same, which shows that the cache changed only the speed.
  4. unit_cost is pure: the same id always gives the same cost. That is what makes it safe to cache.

Alternative: better still, read products.csv once into a dict before the loop: costs = {row["product_id"]: float(row["unit_cost"]) for row in csv.DictReader(f)}. That is 1 read. Use a cache when you cannot load everything up front, for example with a slow API that you query one id at a time.

M09-C09 · Configure validators with partial

Section titled “M09-C09 · Configure validators with partial”
Core

data/config.json holds the validation thresholds of the pipeline: min_quantity, max_quantity and max_discount, and the missing-value tokens in cleaning.na_values. Write one general function in_range(value, low, high). Build quantity_ok and discount_ok from it with functools.partial and the config values. Check every row of data/sales_raw.csv: count the bad quantities (and list them), the missing discounts and the bad discounts.

Expected output
{'low': 1, 'high': 50}
10 bad quantities: [-3, -2, -2, -2, -1, -1, 250, 500, 999, 1000]
24 missing discounts, 0 bad discounts
Starter
import csv
import json
from functools import partial
from pathlib import Path
def in_range(value, low, high):
return low <= value <= high
config = json.loads(Path("data/config.json").read_text(encoding="utf-8"))
# TODO: build quantity_ok and discount_ok with partial
# TODO: check each row of data/sales_raw.csv and print the counts
Hint 1

thresholds = config["thresholds"]. Then partial(in_range, low=thresholds["min_quantity"], high=thresholds["max_quantity"]). A discount can be as low as 0.0.

Hint 2

quantity is always a number in this file, but discount can be one of the tokens in config["cleaning"]["na_values"]. Check for a missing value before you call float().

Solution
import csv
import json
from functools import partial
from pathlib import Path
def in_range(value, low, high):
return low <= value <= high
config = json.loads(Path("data/config.json").read_text(encoding="utf-8"))
thresholds = config["thresholds"]
na_values = set(config["cleaning"]["na_values"])
quantity_ok = partial(
in_range, low=thresholds["min_quantity"], high=thresholds["max_quantity"]
)
discount_ok = partial(in_range, low=0.0, high=thresholds["max_discount"])
bad_quantities, missing_discounts, bad_discounts = [], 0, 0
with open("data/sales_raw.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
quantity = int(row["quantity"])
if not quantity_ok(quantity):
bad_quantities.append(quantity)
if row["discount"] in na_values:
missing_discounts += 1
elif not discount_ok(float(row["discount"])):
bad_discounts += 1
print(quantity_ok.keywords)
print(len(bad_quantities), "bad quantities:", sorted(bad_quantities))
print(missing_discounts, "missing discounts,", bad_discounts, "bad discounts")
assert len(bad_quantities) == 10
assert missing_discounts == 24
Output
{'low': 1, 'high': 50}
10 bad quantities: [-3, -2, -2, -2, -1, -1, 250, 500, 999, 1000]
24 missing discounts, 0 bad discounts

How it works:

  1. in_range knows nothing about quantities or discounts. partial turns it into two specific checks by fixing low and high.
  2. The thresholds come from the config file, so changing the rules needs no code change.
  3. quantity_ok.keywords shows the fixed settings, which helps when you debug a check.
  4. The file has 6 negative and 4 absurd quantities, and 24 missing discounts ("", N/A or -). Every present discount is valid.

Alternative: a dict of named checks keeps the loop short when there are many columns: checks = {"quantity": quantity_ok, "discount": discount_ok}, then loop over checks.items(). Module 26 does the same validation with pandas.

Core

The order_date column of data/sales_raw.csv mixes three formats. data/config.json lists them in cleaning.date_formats. Write parse_date(text) that tries each format with datetime.strptime and returns the date and the format that worked. Count how many dates used each format, and print the earliest and the latest date. Finally, parse 07/01/2023 and print it on the same line with the format %d %B %Y.

Expected output
%Y-%m-%d 723
%d/%m/%Y 276
%B %d, %Y 201
2023-01-01 2024-12-31 07 January 2023
Starter
import csv
import json
from collections import Counter
from datetime import datetime
from pathlib import Path
config = json.loads(Path("data/config.json").read_text(encoding="utf-8"))
formats = config["cleaning"]["date_formats"]
def parse_date(text):
# TODO: try each format; return (date, format); raise ValueError if none fits
...
# TODO: parse every order_date, count the formats, print min and max
Hint 1

datetime.strptime(text, fmt) raises ValueError when the text does not fit fmt. Catch it and try the next format.

Hint 2

Return datetime.strptime(text, fmt).date(), fmt on success. After the loop, raise ValueError(f"unknown date format: {text!r}").

Solution
import csv
import json
from collections import Counter
from datetime import datetime
from pathlib import Path
config = json.loads(Path("data/config.json").read_text(encoding="utf-8"))
formats = config["cleaning"]["date_formats"]
def parse_date(text):
for fmt in formats:
try:
return datetime.strptime(text, fmt).date(), fmt
except ValueError:
continue
raise ValueError(f"unknown date format: {text!r}")
used = Counter()
dates = []
with open("data/sales_raw.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
day, fmt = parse_date(row["order_date"])
used[fmt] += 1
dates.append(day)
for fmt, count in used.most_common():
print(f"{fmt:<10}{count:>5}")
print(min(dates), max(dates), parse_date("07/01/2023")[0].strftime("%d %B %Y"))
assert used.total() == 1200
assert min(dates).year == 2023 and max(dates).year == 2024
Output
%Y-%m-%d 723
%d/%m/%Y 276
%B %d, %Y 201
2023-01-01 2024-12-31 07 January 2023

How it works:

  1. parse_date tries the formats in order. The first one that fits wins; a ValueError means “try the next”.
  2. If no format fits, the function raises its own ValueError with the bad text, so a new format cannot slip through silently.
  3. 07/01/2023 is day first (%d/%m/%Y), so it is 7 January, not July 1. Only %d/%m/%Y fits it here. If the config had both %d/%m/%Y and %m/%d/%Y, the first one listed would win, and nothing would warn you.
  4. Every one of the 1,200 dates parsed, and all of them fall in 2023 and 2024.

Alternative: pandas parses the same column in one call: pd.to_datetime(df["order_date"], format="mixed", dayfirst=True) (module 26). The loop shows what such a call does for you.

M09-C11 · Fix the bug: the night shift across the DST change

Section titled “M09-C11 · Fix the bug: the night shift across the DST change”
Core

Fix the bug: a New York warehouse pays its night shift by the hour (21.50 USD). On the night of 2024-11-02 to 11-03 the shift ran from 22:00 to 06:00 local time. Clocks went back one hour at 02:00 that night, so the staff worked 9 real hours. The code below pays 8 hours. Fix it.

Expected output
EDT -> EST
Shift: 9.0 hours, pay 193.50 USD
Starter
from datetime import datetime
from zoneinfo import ZoneInfo
new_york = ZoneInfo("America/New_York")
start = datetime(2024, 11, 2, 22, 0, tzinfo=new_york)
end = datetime(2024, 11, 3, 6, 0, tzinfo=new_york)
hours = (end - start).total_seconds() / 3600
print(start.tzname(), "->", end.tzname())
print(f"Shift: {hours} hours, pay {hours * 21.50:.2f} USD") # 8.0 hours
# TODO: fix the bug
Hint 1

Look at the two tzname() values. Python subtracts two datetimes that share a time zone as wall-clock times, without the DST change.

Hint 2

Convert both ends to UTC with .astimezone(UTC) (from datetime import UTC) before you subtract.

Solution
from datetime import UTC, datetime
from zoneinfo import ZoneInfo
new_york = ZoneInfo("America/New_York")
start = datetime(2024, 11, 2, 22, 0, tzinfo=new_york)
end = datetime(2024, 11, 3, 6, 0, tzinfo=new_york)
elapsed = end.astimezone(UTC) - start.astimezone(UTC)
hours = elapsed.total_seconds() / 3600
print(start.tzname(), "->", end.tzname())
print(f"Shift: {hours} hours, pay {hours * 21.50:.2f} USD")
assert hours == 9.0
assert end - start != elapsed # the wall-clock difference is wrong
Output
EDT -> EST
Shift: 9.0 hours, pay 193.50 USD

How it works:

  1. The shift starts in daylight time (EDT, UTC−4) and ends in standard time (EST, UTC−5).
  2. end - start with the same tzinfo compares wall-clock times: 22:00 to 06:00 is 8 hours.
  3. In UTC, the shift runs from 02:00 to 11:00: 9 real hours. Converting first gives the true elapsed time.
  4. The second assert documents the trap: the two differences really are different.

Alternative: store the shift times in UTC from the start, for example as the badge system records them, and convert to New York time only on the payslip. Then subtraction is always correct.

M09-C12 · Load times per file from the log

Section titled “M09-C12 · Load times per file from the log”
Core

The loader in data/logs/app.log writes lines such as Loaded 20000 rows from sales.csv in 0.55s. Write a compiled regex with named groups for the row count, the file name and the seconds. For each file, print the number of loads, the distinct row counts and the mean and maximum load time.

Expected output
customers.csv 9 loads rows [5000] mean 0.31 s max 0.41 s
products.csv 9 loads rows [30] mean 0.21 s max 0.30 s
sales.csv 9 loads rows [20000] mean 0.60 s max 0.68 s
Starter
import re
import statistics
from collections import defaultdict
LOADED = re.compile(r"TODO") # TODO: named groups rows, file, seconds
times = defaultdict(list)
row_counts = defaultdict(set)
# TODO: search each line of data/logs/app.log and fill the two dicts
# TODO: print one line per file
Hint 1

(?P<rows>\d+) captures the row count. A file name has no spaces: (?P<file>\S+). Seconds are digits and a dot: (?P<seconds>[\d.]+).

Hint 2

Use LOADED.search(line), because the message is in the middle of the line. match["seconds"] is a string; convert it with float().

Solution
import re
import statistics
from collections import defaultdict
LOADED = re.compile(
r"Loaded (?P<rows>\d+) rows from (?P<file>\S+) in (?P<seconds>[\d.]+)s"
)
times = defaultdict(list)
row_counts = defaultdict(set)
with open("data/logs/app.log", encoding="utf-8") as f:
for line in f:
match = LOADED.search(line)
if match:
times[match["file"]].append(float(match["seconds"]))
row_counts[match["file"]].add(int(match["rows"]))
for file, seconds in sorted(times.items()):
print(f"{file:<14}{len(seconds):>2} loads rows {sorted(row_counts[file])} "
f"mean {statistics.mean(seconds):.2f} s max {max(seconds):.2f} s")
assert sum(len(s) for s in times.values()) == 27
Output
customers.csv 9 loads rows [5000] mean 0.31 s max 0.41 s
products.csv 9 loads rows [30] mean 0.21 s max 0.30 s
sales.csv 9 loads rows [20000] mean 0.60 s max 0.68 s

How it works:

  1. The pattern spells out the fixed words (Loaded, rows from, in) and captures the three variable parts with names.
  2. search() finds the message anywhere in the line; other lines return None and are skipped.
  3. times collects the load times and row_counts the distinct row counts per file. The row counts never change, so each file was the same size on every run.
  4. 9 pipeline runs × 3 files = 27 loads, which the assert checks.

Alternative: re.findall() on the whole file text returns (rows, file, seconds) tuples in one call: re.findall(LOADED, Path("data/logs/app.log").read_text(encoding="utf-8")). It is compact, but it holds the whole file in memory.

M09-C13 · Mask personal data before sharing a log

Section titled “M09-C13 · Mask personal data before sharing a log”
Core

Before you send log lines to an outside vendor, mask the personal data. In the first 3 API lines of data/logs/app.log, replace each email with its first letter, *** and the domain (p***@example.com), and each IP address with its first two parts and x.x (10.0.x.x). Print the masked lines without their timestamps.

Expected output
INFO [api] 10.0.x.x GET /api/v1/reports/2024-04 200 87ms user=p***@example.com
INFO [api] 10.0.x.x GET /api/v1/products?page=3 200 88ms user=p***@example.com
INFO [api] 172.16.x.x POST /api/v1/predict 201 93ms user=m***@example.org
Starter
import re
EMAIL = re.compile(r"TODO") # TODO: group 1 = first letter, group 2 = domain
IP = re.compile(r"TODO") # TODO: group 1 = the first two parts
# TODO: take the first 3 lines that contain "[api]" and mask them
Hint 1

For an email, capture two parts: the first character of the name, and the domain after @. Let the rest of the name (word characters and dots) match outside any group, so the replacement drops it. In the replacement string, \1 and \2 insert the captured groups.

Hint 2

An IP address is four numbers of 1 to 3 digits joined by dots. Capture the first two numbers with their dot in one group, and anchor the pattern with \b on both sides. Remember that a literal dot is \.. Count the characters of the timestamp to know where to slice.

Solution
import re
EMAIL = re.compile(r"(\w)[\w.]*@([\w.]+)")
IP = re.compile(r"\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b")
def mask(line):
line = EMAIL.sub(r"\1***@\2", line)
return IP.sub(r"\1.x.x", line)
masked = []
with open("data/logs/app.log", encoding="utf-8") as f:
for line in f:
if "[api]" in line:
masked.append(mask(line.rstrip("\n")))
if len(masked) == 3:
break
for line in masked:
print(line[24:])
assert all("@example." in line and ".x.x" in line for line in masked)
assert not any(re.search(r"\w{2,}@", line) for line in masked)
Output
INFO [api] 10.0.x.x GET /api/v1/reports/2024-04 200 87ms user=p***@example.com
INFO [api] 10.0.x.x GET /api/v1/products?page=3 200 88ms user=p***@example.com
INFO [api] 172.16.x.x POST /api/v1/predict 201 93ms user=m***@example.org

How it works:

  1. EMAIL captures the first character and the domain. [\w.]* eats the rest of the user name, which the replacement drops.
  2. IP captures the first two numbers. \b on both sides stops the pattern from matching inside a longer number.
  3. sub() replaces every match in the line. The order matters little here, because emails and IPs cannot overlap.
  4. The second assert checks that no line still has two or more word characters before an @.

Alternative: pass a function as the replacement for more complex rules: EMAIL.sub(lambda m: m[1] + "***@" + m[2], line). A function can also hash the address, so the vendor can still count distinct users.

M09-C14 · Interpret: a reproducible train/test split

Section titled “M09-C14 · Interpret: a reproducible train/test split”
Core

Interpret a result: split the 5,000 customers of data/customers.csv into 80% training and 20% test data with random.Random(42). Print the sizes, the first 3 test ids and the churn rate of each part. Then build the split again with a new Random(42) and check that it is identical. Finally, explain in one sentence why the two churn rates differ.

Expected output
4000 1000 ['C00230', 'C03262', 'C01329']
churn: train 19.25%, test 19.30%
same split: True
The test set is a random sample of 1,000, so its rate varies around 19.26%.
Starter
import csv
import random
with open("data/customers.csv", encoding="utf-8", newline="") as f:
customers = [(row["customer_id"], int(row["churned"])) for row in csv.DictReader(f)]
# TODO: write split(records, seed) that shuffles a copy and cuts it at 80%
# TODO: print the sizes, 3 test ids and the churn rate of each part
# TODO: check that a second split with seed 42 is identical
Hint 1

Copy the list before you shuffle it: shuffled = records[:], then random.Random(seed).shuffle(shuffled). shuffle works in place and returns None.

Hint 2

The churn rate of a part is sum(churned for _, churned in part) / len(part).

Solution
import csv
import random
with open("data/customers.csv", encoding="utf-8", newline="") as f:
customers = [(row["customer_id"], int(row["churned"])) for row in csv.DictReader(f)]
def split(records, seed, train_share=0.8):
shuffled = records[:]
random.Random(seed).shuffle(shuffled)
cut = int(len(shuffled) * train_share)
return shuffled[:cut], shuffled[cut:]
def churn_rate(part):
return sum(churned for _, churned in part) / len(part)
train, test = split(customers, seed=42)
print(len(train), len(test), [cid for cid, _ in test[:3]])
print(f"churn: train {churn_rate(train):.2%}, test {churn_rate(test):.2%}")
again_train, again_test = split(customers, seed=42)
print("same split:", again_test == test)
print("The test set is a random sample of 1,000, so its rate varies around 19.26%.")
assert {cid for cid, _ in train}.isdisjoint(cid for cid, _ in test)
assert len(train) + len(test) == len(customers)
Output
4000 1000 ['C00230', 'C03262', 'C01329']
churn: train 19.25%, test 19.30%
same split: True
The test set is a random sample of 1,000, so its rate varies around 19.26%.

How it works:

  1. split() shuffles a copy, so the original order of customers stays intact.
  2. A new Random(42) produces the same sequence of random numbers, so the shuffle and the split are identical: same split: True.
  3. The first assert checks that no customer is in both parts. That is the property that keeps a test score honest.
  4. The overall churn rate is 19.26%. Each part is a random sample, so its rate wanders a little around that value. A stratified split (module 34) forces equal rates.

Alternative: rng.sample(customers, k=1000) draws the test set directly; the training set is then everything else. scikit-learn’s train_test_split(..., random_state=42, stratify=y) does the whole job in one call.

Challenge

In data/sensors.csv, each reading has a status (ok, warn or fail). An alert run is a sequence of consecutive non-ok readings of one sensor. For each sensor, print the status counts, the number of alert runs, the length of its longest alert run, the run’s first and last timestamps and its duration. A run of n readings lasts n × 10 minutes.

Expected output
Sensor ok warn fail runs longest alert run
S1 2002 14 0 14 1 reading, 05-02 00:20 to 05-02 00:20 (0:10:00)
S2 1994 17 5 22 1 reading, 05-01 00:40 to 05-01 00:40 (0:10:00)
S3 1994 22 0 22 1 reading, 05-01 10:40 to 05-01 10:40 (0:10:00)
S4 1597 400 19 57 272 readings, 05-13 02:40 to 05-14 23:50 (1 day, 21:20:00)
Starter
import csv
from collections import Counter, defaultdict, namedtuple
from datetime import datetime, timedelta
from itertools import groupby
Reading = namedtuple("Reading", ["timestamp", "status"])
by_sensor = defaultdict(list)
# TODO: fill by_sensor with Reading records, in file order
# TODO: for each sensor: Counter of statuses, then groupby on "status != ok"
# TODO: keep the longest alert run and print the report
Hint 1

The file is sorted by timestamp, so each sensor’s list is in time order. Group with groupby(readings, key=lambda r: r.status != "ok"): the key is True for an alert run.

Hint 2

Turn each alert group into a list, run = list(group), and keep it if it is longer than the best so far. run[0].timestamp and run[-1].timestamp are its ends.

Hint 3

datetime.fromisoformat(run[0].timestamp) parses the timestamp. The duration is len(run) * timedelta(minutes=10); check it against last - first + timedelta(minutes=10).

Solution
import csv
from collections import Counter, defaultdict, namedtuple
from datetime import datetime, timedelta
from itertools import groupby
Reading = namedtuple("Reading", ["timestamp", "status"])
STEP = timedelta(minutes=10)
by_sensor = defaultdict(list)
with open("data/sensors.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
by_sensor[row["sensor_id"]].append(Reading(row["timestamp"], row["status"]))
print(f"{'Sensor':<7}{'ok':>5}{'warn':>5}{'fail':>5}{'runs':>5} longest alert run")
for sensor, readings in sorted(by_sensor.items()):
counts = Counter(r.status for r in readings)
runs, longest = 0, []
for is_alert, group in groupby(readings, key=lambda r: r.status != "ok"):
run = list(group)
if is_alert:
runs += 1
if len(run) > len(longest):
longest = run
first = datetime.fromisoformat(longest[0].timestamp)
last = datetime.fromisoformat(longest[-1].timestamp)
duration = len(longest) * STEP
assert last - first + STEP == duration # no gaps inside the run
unit = "reading" if len(longest) == 1 else "readings"
status_cols = f"{counts['ok']:>5}{counts['warn']:>5}{counts['fail']:>5}"
print(f"{sensor:<7}{status_cols}{runs:>5} "
f"{len(longest)} {unit}, {first:%m-%d %H:%M} to {last:%m-%d %H:%M}"
f" ({duration})")
assert sum(len(r) for r in by_sensor.values()) == 8064
Output
Sensor ok warn fail runs longest alert run
S1 2002 14 0 14 1 reading, 05-02 00:20 to 05-02 00:20 (0:10:00)
S2 1994 17 5 22 1 reading, 05-01 00:40 to 05-01 00:40 (0:10:00)
S3 1994 22 0 22 1 reading, 05-01 10:40 to 05-01 10:40 (0:10:00)
S4 1597 400 19 57 272 readings, 05-13 02:40 to 05-14 23:50 (1 day, 21:20:00)

How it works:

  1. defaultdict(list) splits the file into one time-ordered list per sensor. Each reading is a small named tuple.
  2. Counter gives the status mix of each sensor in one line.
  3. groupby with the key status != "ok" yields alternating runs of normal and alert readings. Only alert runs (is_alert is True) are counted and compete for the longest.
  4. The duration comes from the count of readings. The assert inside the loop checks it against the timestamps, which proves the run has no gaps.
  5. Format specs work on datetimes inside f-strings: {first:%m-%d %H:%M} calls strftime for you.
  6. S1, S2 and S3 have as many alert runs as alert readings: their alerts are isolated spikes, never two in a row. S4’s longest run lasts 272 readings, from May 13 at 02:40 to the end of the data, because its vibration stays high once it wears out.

Alternative: treat warn and fail separately with the key r.status. Then groupby gives runs per status, and you can report, for example, the longest fail run. A rolling window, as in the lesson’s Example 2, is the tool for “4 of the last 6”, which tolerates single ok readings inside a run.

M09-X02 · A weekday and week calendar of sales

Section titled “M09-X02 · A weekday and week calendar of sales”
Challenge

For 2024 in data/sales.csv, compute the revenue of each calendar day. Then report: the mean daily revenue per weekday (Monday first), the number of days per weekday, and the ISO week with the highest revenue, with its Monday and Sunday dates. An ISO week runs from Monday to Sunday and is numbered 1 to 52 or 53; date.isocalendar() returns it.

Expected output
Mon 53 days mean 4,846.89
Tue 53 days mean 4,393.95
Wed 52 days mean 4,340.10
Thu 52 days mean 4,639.28
Fri 52 days mean 6,059.43
Sat 52 days mean 6,659.82
Sun 52 days mean 6,400.78
Best ISO week: 2024-W48 (2024-11-25 to 2024-12-01), 98,491.04 USD
Weeks: 53 | first: (2024, 1) | last: (2025, 1)
Starter
import csv
import statistics
from collections import defaultdict
from datetime import date, timedelta
daily = defaultdict(float)
# TODO: revenue per date for 2024 (keys: date objects)
# TODO: mean revenue per weekday, Monday first, with the number of days
# TODO: revenue per ISO week; print the best week with its Monday and Sunday
Hint 1

date.fromisoformat(row["order_date"]) gives a date. day.weekday() is 0 for Monday, and day.strftime("%a") gives the short name.

Hint 2

Group the daily totals in defaultdict(list) by day.weekday(), then take statistics.mean() of each list. For weeks, sum into defaultdict(float) keyed by the ISO year and the week: day.isocalendar()[:2]. Check what date(2024, 12, 30).isocalendar() returns.

Hint 3

date.fromisocalendar(iso_year, week, 1) returns the Monday of an ISO week. Its Sunday is 6 days later.

Solution
import csv
import statistics
from collections import defaultdict
from datetime import date, timedelta
daily = defaultdict(float)
with open("data/sales.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
day = date.fromisoformat(row["order_date"])
if day.year == 2024:
daily[day] += float(row["revenue"])
by_weekday = defaultdict(list)
weekly = defaultdict(float)
for day, revenue in daily.items():
by_weekday[day.weekday()].append(revenue)
weekly[day.isocalendar()[:2]] += revenue # (ISO year, week)
for weekday in sorted(by_weekday):
values = by_weekday[weekday]
name = date(2024, 1, 1 + weekday).strftime("%a") # 2024-01-01 is a Monday
print(f"{name} {len(values)} days mean {statistics.mean(values):>9,.2f}")
best_year, best_week = max(weekly, key=weekly.get)
monday = date.fromisocalendar(best_year, best_week, 1)
sunday = monday + timedelta(days=6)
print(f"Best ISO week: {best_year}-W{best_week} ({monday} to {sunday}), "
f"{weekly[best_year, best_week]:,.2f} USD")
print("Weeks:", len(weekly), "| first:", min(weekly), "| last:", max(weekly))
assert len(daily) == 366
assert sum(len(v) for v in by_weekday.values()) == 366
assert (2025, 1) in weekly # Dec 30-31, 2024 belong to ISO week 1 of 2025
Output
Mon 53 days mean 4,846.89
Tue 53 days mean 4,393.95
Wed 52 days mean 4,340.10
Thu 52 days mean 4,639.28
Fri 52 days mean 6,059.43
Sat 52 days mean 6,659.82
Sun 52 days mean 6,400.78
Best ISO week: 2024-W48 (2024-11-25 to 2024-12-01), 98,491.04 USD
Weeks: 53 | first: (2024, 1) | last: (2025, 1)

How it works:

  1. The dict keys are date objects, so the weekday and the ISO week come from methods instead of string slicing.
  2. 2024 is a leap year with 366 days: 52 full weeks and 2 days. It starts on a Monday and ends on a Tuesday, so Monday and Tuesday occur 53 times.
  3. Saturday has the highest mean daily revenue, as the data dictionary describes.
  4. date(2024, 1, 1 + weekday) turns a weekday number into its name, because January 1, 2024 is a Monday.
  5. The best ISO week is week 48, Monday November 25 to Sunday December 1: the week of Black Friday (November 29) and the weekend after it.
  6. date.fromisocalendar() converts back from (year, week, weekday) to a date.
  7. December 30 and 31, 2024 belong to ISO week 1 of 2025: date(2024, 12, 30).isocalendar() is (2025, 1, 1). Keyed by the week number alone, they would be added to week 1 of 2024 and almost double it. The key (ISO year, week) keeps them apart, so the last key is (2025, 1), a partial week of 2 days.

Alternative: calendar.day_abbr[weekday] (from the calendar module) gives the weekday names directly. Watch out near New Year in every dataset, even a single year: the last days of December can belong to week 1 of the next ISO year (as here), and the first days of January to week 52 or 53 of the year before. Always key ISO weeks by (ISO year, week).

M09-X03 · A cached grid search over three thresholds

Section titled “M09-X03 · A cached grid search over three thresholds”
Challenge

Extend the lesson’s churn rule to three conditions: tenure at most T months, logins at most L in 30 days and at least K support tickets. Search all 27 rules with T in (6, 12, 24), L in (5, 10, 20) and K in (1, 2, 3) and report the best F1 score.

Each condition selects a set of customers. Write one cached function selected(column, low, high) that returns the frozenset of row numbers whose value lies in [low, high]. Build the three conditions from it with partial, combine their sets with reduce, and use cache_info() to show how many sets were really computed.

Expected output
27 rules; best (T, L, K): (6, 20, 1)
precision 0.482, recall 0.400, F1 0.437
CacheInfo(hits=72, misses=9, maxsize=None, currsize=9)
Starter
import csv
from functools import cache, partial, reduce
from itertools import product
with open("data/customers.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
churned = frozenset(i for i, row in enumerate(rows) if row["churned"] == "1")
@cache
def selected(column, low, high):
# TODO: frozenset of row numbers i with low <= int(rows[i][column]) <= high
...
# TODO: tenure_at_most, logins_at_most, tickets_at_least with partial
# TODO: for each (T, L, K) in product(...): intersect the three sets, compute F1
# TODO: print the best rule, its precision, recall and F1, and cache_info()
Hint 1

partial(selected, "tenure_months", 0) fixes column and low, so tenure_at_most(12) means selected("tenure_months", 0, 12). For “at least K tickets”, fix the high end with a keyword: partial(selected, "support_tickets", high=99), then call it with low=K.

Hint 2

reduce(frozenset.intersection, [a, b, c]) intersects the three sets. The true positives are len(flagged & churned).

Hint 3

The grid makes 81 calls (27 rules × 3 conditions), but there are only 9 distinct (column, low, high) combinations. cache_info() must show 9 misses.

Solution
import csv
from functools import cache, partial, reduce
from itertools import product
with open("data/customers.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
churned = frozenset(i for i, row in enumerate(rows) if row["churned"] == "1")
@cache
def selected(column, low, high):
return frozenset(i for i, row in enumerate(rows) if low <= int(row[column]) <= high)
tenure_at_most = partial(selected, "tenure_months", 0)
logins_at_most = partial(selected, "logins_last_30d", 0)
tickets_at_least = partial(selected, "support_tickets", high=99)
def score(flagged):
true_pos = len(flagged & churned)
precision = true_pos / len(flagged)
recall = true_pos / len(churned)
return precision, recall, 2 * precision * recall / (precision + recall)
results = {}
for rule in product((6, 12, 24), (5, 10, 20), (1, 2, 3)):
tenure, logins, tickets = rule
sets = [
tenure_at_most(tenure), logins_at_most(logins), tickets_at_least(low=tickets)
]
results[rule] = score(reduce(frozenset.intersection, sets))
best = max(results, key=lambda rule: results[rule][2])
precision, recall, f1 = results[best]
print(len(results), "rules; best (T, L, K):", best)
print(f"precision {precision:.3f}, recall {recall:.3f}, F1 {f1:.3f}")
print(selected.cache_info())
info = selected.cache_info()
assert info.hits + info.misses == 81 and info.misses == 9
Output
27 rules; best (T, L, K): (6, 20, 1)
precision 0.482, recall 0.400, F1 0.437
CacheInfo(hits=72, misses=9, maxsize=None, currsize=9)

How it works:

  1. selected scans 5,000 rows once per distinct (column, low, high). It returns a frozenset, which is immutable, so the cached sets cannot be changed by a caller.
  2. partial builds three readable conditions from one function. tickets_at_least fixes high with a keyword and leaves low open.
  3. Each rule intersects three cached sets with reduce, which is much faster than a new scan.
  4. 27 rules × 3 conditions = 81 calls, but only 3 + 3 + 3 = 9 distinct ones: 9 misses (real scans) and 72 hits.
  5. Interpret the result: the best three-condition rule (F1 0.437) is no better than the two-condition rule (12, 20) of the lesson’s sweep (F1 0.443). Each extra and condition can only shrink the flagged set: it trades recall for precision. More conditions are not automatically a better model.

Alternative: with NumPy, each condition is a Boolean array and & combines them for all rows at once (module 23). The cache idea stays the same: compute each building block once, reuse it in every combination.

M09-X04 · Simulate the stock-out risk of a product

Section titled “M09-X04 · Simulate the stock-out risk of a product”
Challenge

A store restocks Wireless Earbuds (P001) once a week. How many units should it hold so that the risk of running out within a week is at most 5%? Use a Monte Carlo simulation: a method that answers a question about chance by simulating it many times with random numbers.

  1. From data/sales.csv, build the units sold of P001 on every day of 2024, including days with no sale (0 units). Use datetime to walk the 366 days.
  2. With random.Random(42), simulate 5,000 weeks: each week’s demand is the sum of 7 days drawn with replacement from the daily list.
  3. For stock levels 15 to 30 in steps of 5, print the share of weeks in which demand is larger than the stock. Then print the smallest stock with a risk of at most 5%.
Expected output
366 days, 69 without a sale, 803 units
weekly demand: mean 15.4, 7 x daily mean 15.4
stock 15: risk 42.6%
stock 20: risk 16.5%
stock 25: risk 5.6%
stock 30: risk 2.4%
smallest stock with risk <= 5%: 26
Starter
import csv
import random
import statistics
from collections import Counter
from datetime import date, timedelta
units = Counter()
# TODO: units of P001 per date for 2024
# TODO: daily list over all 366 days (0 when missing)
rng = random.Random(42)
# TODO: simulate 5,000 weeks of demand
# TODO: print the risk for each stock level and the smallest safe stock
Hint 1

Walk the year with day = date(2024, 1, 1) and day += timedelta(days=1) while day.year == 2024. units[day.isoformat()] is 0 for a day without sales, because units is a Counter.

Hint 2

One week of demand is sum(rng.choices(daily, k=7)). A list comprehension builds the 5,000 weeks.

Hint 3

The risk at a stock level is sum(week > stock for week in weeks) / len(weeks). For the smallest safe stock, loop over range(10, 41) and stop at the first level with a risk of at most 0.05.

Solution
import csv
import random
import statistics
from collections import Counter
from datetime import date, timedelta
units = Counter()
with open("data/sales.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["product_id"] == "P001" and row["order_date"].startswith("2024"):
units[row["order_date"]] += int(row["quantity"])
daily = []
day = date(2024, 1, 1)
while day.year == 2024:
daily.append(units[day.isoformat()])
day += timedelta(days=1)
print(len(daily), "days,", daily.count(0), "without a sale,", sum(daily), "units")
rng = random.Random(42)
weeks = [sum(rng.choices(daily, k=7)) for _ in range(5000)]
print(f"weekly demand: mean {statistics.mean(weeks):.1f}, "
f"7 x daily mean {7 * statistics.mean(daily):.1f}")
def risk(stock):
return sum(week > stock for week in weeks) / len(weeks)
for stock in range(15, 31, 5):
print(f"stock {stock}: risk {risk(stock):.1%}")
safe = next(stock for stock in range(10, 41) if risk(stock) <= 0.05)
print("smallest stock with risk <= 5%:", safe)
assert len(daily) == 366 and sum(daily) == 803
assert risk(safe) <= 0.05 < risk(safe - 1)
Output
366 days, 69 without a sale, 803 units
weekly demand: mean 15.4, 7 x daily mean 15.4
stock 15: risk 42.6%
stock 20: risk 16.5%
stock 25: risk 5.6%
stock 30: risk 2.4%
smallest stock with risk <= 5%: 26

How it works:

  1. The Counter gives 0 for days without a sale, so the daily list covers all 366 days. Leaving out the zero days would overstate demand.
  2. rng.choices(daily, k=7) draws 7 days with replacement. Their sum is one simulated week. This keeps the real shape of daily demand, including slow days and bulk orders.
  3. The mean of the simulated weeks matches 7 × the daily mean, a quick sanity check of the simulation.
  4. The risk falls as the stock rises. next() with a generator expression finds the first stock level that meets the target. Module 10 explains it.
  5. The last assert checks that the answer is really the smallest level: one unit less breaks the 5% target.

Alternative: a formula approach assumes a distribution, for example a normal distribution with the weekly mean and standard deviation: statistics.NormalDist(mu, sigma).inv_cdf(0.95). Daily sales are skewed and contain zeros, so the simulation is more faithful. Seasonality is a limit of both: December weeks sell more than the yearly average. Module 40 forecasts demand with the season.

M09-X05 · Archive and verify a report run

Section titled “M09-X05 · Archive and verify a report run”
Challenge

Write the core of a nightly archive job:

  1. Read the archive root from the environment variable ARCHIVE_ROOT (default output/archive). The run date is 2024-07-01: build the folder name reports_20240701 from a date.
  2. Start from a clean folder (shutil.rmtree with ignore_errors=True), then copy the six files of data/reports/ into it with shutil.copy2.
  3. Write manifest.json into the folder. A manifest is a list of the files that a folder must contain, with a fact to check for each one. Here it is a dict that maps each file name to its size in bytes.
  4. Run a checker in a child process with subprocess.run([sys.executable, "-c", CHECKER], ...). Pass the folder to the child in the environment variable CHECK_DIR. The checker compares each file with the manifest. It prints OK <n> files or exits with sys.exit("size mismatch: <name>").
  5. Run the check, then damage one copy (append a line to 2024-03.csv) and run it again. Catch the CalledProcessError and print its exit code and message.
  6. Restore the file from data/reports/, check again and zip the folder with shutil.make_archive. Print only the archive’s file name.
Expected output
output/archive/reports_20240701 6 files
check 1: OK 6 files
check 2: exit code 1 - size mismatch: 2024-03.csv
check 3: OK 6 files
reports_20240701.zip
Starter
import json
import os
import shutil
import subprocess
import sys
from datetime import date
from pathlib import Path
CHECKER = """
# TODO: read CHECK_DIR, load manifest.json, compare sizes, print OK or sys.exit(...)
"""
# TODO: steps 1-6
Hint 1

f"reports_{run_date:%Y%m%d}" formats a date inside an f-string. Path(os.environ.get("ARCHIVE_ROOT", "output/archive")) / name builds the folder path.

Hint 2

Give the child its own environment: env={**os.environ, "CHECK_DIR": str(folder)}. Use capture_output=True, text=True, check=True.

Hint 3

sys.exit("message") in the child writes the message to stderr and exits with code 1. In the parent, error.stderr.strip() is that message.

Solution
import json
import os
import shutil
import subprocess
import sys
from datetime import date
from pathlib import Path
CHECKER = """
import json, os, sys
from pathlib import Path
folder = Path(os.environ["CHECK_DIR"])
manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8"))
for name, size in sorted(manifest.items()):
if (folder / name).stat().st_size != size:
sys.exit(f"size mismatch: {name}")
print(f"OK {len(manifest)} files")
"""
run_date = date(2024, 7, 1)
root = Path(os.environ.get("ARCHIVE_ROOT", "output/archive"))
folder = root / f"reports_{run_date:%Y%m%d}"
shutil.rmtree(folder, ignore_errors=True)
folder.mkdir(parents=True)
sources = sorted(Path("data/reports").glob("*.csv"))
for src in sources:
shutil.copy2(src, folder)
manifest = {src.name: src.stat().st_size for src in sources}
(folder / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
print(folder.as_posix(), len(manifest), "files")
def check():
result = subprocess.run(
[sys.executable, "-c", CHECKER],
env={**os.environ, "CHECK_DIR": str(folder)},
capture_output=True,
text=True,
check=True,
timeout=60,
)
return result.stdout.strip()
print("check 1:", check())
with open(folder / "2024-03.csv", "a", encoding="utf-8") as f:
f.write("O999999,2024-03-31,S01,Test,Books,1,0.0\n")
try:
check()
except subprocess.CalledProcessError as error:
print("check 2: exit code", error.returncode, "-", error.stderr.strip())
shutil.copy2("data/reports/2024-03.csv", folder)
print("check 3:", check())
archive = shutil.make_archive(str(folder), "zip", root_dir=folder)
print(Path(archive).name)
assert Path(archive).stat().st_size > 0
assert check() == "OK 6 files"
Output
output/archive/reports_20240701 6 files
check 1: OK 6 files
check 2: exit code 1 - size mismatch: 2024-03.csv
check 3: OK 6 files
reports_20240701.zip

How it works:

  1. The root comes from the environment with a default, and the folder name from a fixed run date, so a rerun of the same night writes to the same place.
  2. rmtree(..., ignore_errors=True) makes the job idempotent: running it twice gives the same result. Use rmtree only on a folder that your job owns.
  3. The manifest records what a correct copy looks like. The checker is a separate program that trusts only the manifest and the files.
  4. env={**os.environ, "CHECK_DIR": ...} copies the parent’s environment and adds one variable for the child.
  5. The damaged file makes the child exit with a message. check=True turns that into a CalledProcessError with the exit code and stderr.
  6. After the restore the check passes again, and make_archive writes reports_20240701.zip next to the folder.

Alternative: compare a checksum instead of the size: a short value computed from all the bytes of a file. hashlib.sha256(path.read_bytes()).hexdigest() changes when any byte changes, even if the size stays the same. Backup and deploy tools use checksums for exactly this.