Part 1 checkpoint
This checkpoint tests Part 1 as a whole. Each exercise mixes two or more modules, as real tasks do: you read a file, clean the text, group the values, handle the bad lines and print a report. The exercises use the course datasets in data/. They are new tasks, not copies of the module exercises.
How to use it:
- Work without your notes first. Read the task and the expected output, then write your code.
- Stuck for more than 10 minutes? Open one hint at a time.
- Open the solution only after a real attempt. Compare your code with it, not only your output.
- Score yourself with the rubric at the end of the page.
Plan about 5 to 9 hours in total: 10–20 minutes for a warm-up, 20–35 minutes for a core exercise and 40–60 minutes for a challenge. You can split the work over several sessions.
| Exercise | Type | Modules |
|---|---|---|
| P1-01 | Predict the output | 01, 02, 03, 04 |
| P1-02 | Fix the bug | 03, 05, 06, 07 |
| P1-03 | Write the code | 02, 05, 07, 09 |
| P1-04 | Write the code | 02, 04, 05, 07, 09 |
| P1-05 | Write the code | 02, 03, 04, 07, 09 |
| P1-06 | Choose and justify | 04, 05, 07, 09 |
| P1-07 | Refactor | 03, 04, 05, 07 |
| P1-08 | Interpret | 03, 04, 06, 07, 09 |
| P1-09 | Fix the bugs | 01, 04, 05, 07 |
| P1-10 | Write a CLI | 05, 06, 07, 08, 09 |
| P1-11 | Write the code | 03, 04, 05, 06, 07, 09 |
| P1-12 | Predict the output | 03, 04, 05, 06, 09 |
| P1-13 | Write the code | 02, 05, 06, 07, 09 |
| P1-14 | Read a traceback, fix the bug | 03, 06, 07 |
Work in your course project folder with Python 3.12 or newer. The data/ folder from Get the data must be in that folder, because every path on this page is relative to it (data/sales.csv). Run each exercise as its own script, for example python p1_04.py. The exercises use only the standard library. Scripts that write files write to output/, never into data/. The data dictionary describes every dataset: columns, row counts and known quirks.
Each solution ends with assert checks. Add the same checks to your own code: a silent run means that every check passed.
P1-01 · Predict the output: clean a product label
Section titled “P1-01 · Predict the output: clean a product label”Predict the output: the code cleans a padded copy of the P008 label from data/products.csv, as it might arrive from a messy export, and checks a small stock table. Write down what each print() shows, then run the code.
Acceptance criteria:
- Write your prediction for all 7 lines before you run the code.
- Your prediction matches the Output in the solution, line by line.
- For each line you got wrong, you can name the rule and the module that explains it.
label = " Chef's Knife Set "clean = label.strip()print(clean.title())print(clean[:4], clean[-3:])words = clean.split()print(len(words), "-".join(words).lower())stock = {"P008": 0, "P014": 12}print(stock.get("P008") or "sold out")print(stock.get("P099") is None)price = "129.95"print(int(float(price)) // 10, round(float(price) * 2, 1))print(7 / 2, 7 // 2, -7 // 2)# TODO: write your prediction for each print() line before you run itHint 1
title() starts a new word after every character that is not a letter. An apostrophe is not a letter.
Hint 2
or returns its first truthy operand. Is the number 0 truthy? // rounds down, toward minus infinity.
Solution
label = " Chef's Knife Set "clean = label.strip()print(clean.title())print(clean[:4], clean[-3:])words = clean.split()print(len(words), "-".join(words).lower())stock = {"P008": 0, "P014": 12}print(stock.get("P008") or "sold out")print(stock.get("P099") is None)price = "129.95"print(int(float(price)) // 10, round(float(price) * 2, 1))print(7 / 2, 7 // 2, -7 // 2)assert clean.title() == "Chef'S Knife Set"assert stock.get("P008") == 0assert -7 // 2 == -4Chef'S Knife SetChef Set3 chef's-knife-setsold outTrue12 259.93.5 3 -4How it works:
title()capitalizes the first letter after any non-letter, so thesafter the apostrophe becomesS(module 02). To fix product names, capitalize each word ofsplit()instead.clean[:4]is the first 4 characters andclean[-3:]the last 3.strip()removed the spaces first, so the slice does not pick up blanks.split()with no argument splits on runs of whitespace and gives 3 words.join()glues them with-.- P008 has a stock of 0.
0is falsy (module 01), soorreturns"sold out". That is a bug in a real report: the product exists, its stock is just zero. Teststock.get("P008") is Nonewhen you mean “missing” (module 03). get()returnsNonefor the unknown key P099 (module 04), sois NoneisTrue.float("129.95")is 129.95,int()cuts it to 129, and129 // 10is 12.129.95 * 2is 259.9./always gives a float.//rounds down: −3.5 becomes −4, not −3.
P1-02 · Fix the bug: summarize the readings file
Section titled “P1-02 · Fix the bug: summarize the readings file”Fix the bugs: summarize() reads data/readings.txt (one temperature per line, 40 valid values and 3 bad lines) and returns the number of valid readings, the line numbers of the bad lines and the mean. Line 12 of the file holds error, line 24 is empty and line 35 holds n/a. The function gives a wrong mean and wrong line numbers:
def summarize(path): values = [] bad_lines = [] with open(path, encoding="utf-8") as file: lines = file.readlines() for number, line in enumerate(lines): try: values.append(float(line)) except Exception: bad_lines.append(number) mean = sum(values) / len(lines) return len(values), bad_lines, mean
count, bad_lines, mean = summarize("data/readings.txt")print(f"{count} valid readings, mean {mean:.2f} °C")print("Invalid lines:", bad_lines)40 valid readings, mean 19.59 °CInvalid lines: [11, 23, 34]Fix it so that it prints the lines below. Also make it raise a ValueError with a clear message when a file has no valid reading at all.
40 valid readings, mean 21.06 °CInvalid lines: [12, 24, 35]def summarize(path): values = [] bad_lines = [] with open(path, encoding="utf-8") as file: lines = file.readlines() for number, line in enumerate(lines): try: values.append(float(line)) except Exception: bad_lines.append(number) mean = sum(values) / len(lines) return len(values), bad_lines, mean
count, bad_lines, mean = summarize("data/readings.txt")print(f"{count} valid readings, mean {mean:.2f} °C")print("Invalid lines:", bad_lines)# TODO: find and fix the bugs; add the check for a file without valid readingsHint 1
enumerate() counts from 0 unless you pass start=. Editors and sed -n 12p count lines from 1.
Hint 2
The mean of the valid readings divides by the number of valid readings, not by the number of lines. float("error") and float("\n") both raise ValueError.
Solution
def summarize(path): """Read one reading per line and record the lines that are not numbers.
Args: path: Path of a text file with one temperature per line.
Returns: A tuple (valid count, bad line numbers, mean of the valid values).
Raises: ValueError: If the file has no valid reading. """ values = [] bad_lines = [] with open(path, encoding="utf-8") as file: for number, line in enumerate(file, start=1): try: values.append(float(line)) except ValueError: bad_lines.append(number) if not values: raise ValueError(f"{path}: no valid reading in {len(bad_lines)} lines") mean = sum(values) / len(values) return len(values), bad_lines, mean
count, bad_lines, mean = summarize("data/readings.txt")print(f"{count} valid readings, mean {mean:.2f} °C")print("Invalid lines:", bad_lines)assert count == 40assert bad_lines == [12, 24, 35]assert round(mean, 2) == 21.0640 valid readings, mean 21.06 °CInvalid lines: [12, 24, 35]How it works:
enumerate(file, start=1)numbers the lines the way people count them. The loop overfilealso reads one line at a time instead of the whole file (module 07).except ValueErrorcatches only the failed conversions.except Exceptionwould also hide real bugs, for example aNameErrorfrom a typo (module 06).- The old code divided the sum of 40 values by 43 lines. That shrinks the mean by the factor 40/43: 21.06 × 40/43 = 19.59. The result sits close to the minimum, 19.3, far from a typical reading. A mean that low is a sign of a wrong count.
if not values:uses truthiness (module 03): an empty list is falsy. Without the check, an empty file would raise aZeroDivisionError, which says nothing about the real problem.- The function returns a tuple, and the caller unpacks it into three names (module 05).
P1-03 · The five oldest stores
Section titled “P1-03 · The five oldest stores”Write the code: read data/stores.csv, find the five stores that opened first and print them in an aligned table. “Years” is the number of full years each store has been open on 2024-12-31, the snapshot date of the course data. Write a function full_years(start, end) for it.
Store City Region Opened YearsS07 New York East 2008-02-23 16S04 Houston South 2008-11-08 16S01 Chicago North 2009-03-14 15S10 Seattle West 2010-06-19 14S05 Atlanta South 2011-04-16 13import csvfrom datetime import date
SNAPSHOT = date(2024, 12, 31)
def full_years(start, end): """Return the number of whole years from start to end.""" # TODO: subtract the years, minus 1 if the anniversary is still ahead
# TODO: read the stores with csv.DictReader and turn "opened" into a date# TODO: sort by the opening date, keep 5, print the tableHint 1
date.fromisoformat("2008-02-23") turns the text into a date. Dates compare and sort by time.
Hint 2
The anniversary is still ahead when (end.month, end.day) < (start.month, start.day). Tuples compare element by element.
Hint 3
Use the same widths in the header and the rows: f"{'City':<13}" and f"{store['city']:<13}". Numbers align right with >.
Solution
import csvfrom datetime import date
SNAPSHOT = date(2024, 12, 31)
def full_years(start, end): """Return the number of whole years from start to end.""" before_anniversary = (end.month, end.day) < (start.month, start.day) return end.year - start.year - int(before_anniversary)
with open("data/stores.csv", newline="", encoding="utf-8") as file: stores = list(csv.DictReader(file))
for store in stores: store["opened"] = date.fromisoformat(store["opened"])
oldest = sorted(stores, key=lambda store: store["opened"])[:5]print(f"{'Store':<6} {'City':<13} {'Region':<7} {'Opened':<10} {'Years':>5}")for store in oldest: years = full_years(store["opened"], SNAPSHOT) print( f"{store['store_id']:<6} {store['city']:<13} {store['region']:<7} " f"{store['opened']:%Y-%m-%d} {years:>5}" )
assert [s["store_id"] for s in oldest] == ["S07", "S04", "S01", "S10", "S05"]assert full_years(date(2008, 2, 23), SNAPSHOT) == 16assert full_years(date(2024, 6, 15), date(2025, 6, 14)) == 0Store City Region Opened YearsS07 New York East 2008-02-23 16S04 Houston South 2008-11-08 16S01 Chicago North 2009-03-14 15S10 Seattle West 2010-06-19 14S05 Atlanta South 2011-04-16 13How it works:
csv.DictReadergives one dict per row, keyed by the header (module 07). Every value is a string, so the loop convertsopenedto adate(module 09).sorted(..., key=...)orders the dicts by their date, and[:5]keeps the first five (modules 04 and 05).full_years()subtracts the years, then removes one year when the anniversary has not come yet. The last assert checks this edge case: one day before the first anniversary is 0 full years.{store['opened']:%Y-%m-%d}formats a date inside an f-string with astrftimepattern. The width specs<13and>5align the columns (module 02).
Alternative: ISO date strings such as 2008-02-23 sort in time order as plain text, so sorted(stores, key=lambda s: s["opened"]) works before the conversion too. You still need real dates for the year arithmetic.
P1-04 · Ratings by category
Section titled “P1-04 · Ratings by category”Write the code: read data/reviews.csv and print, per category, the number of reviews, the mean rating and the share of 1- and 2-star reviews. Sort the table by mean rating, best first, and add a total row. Then count the reviews whose text contains a line break. The file has 3,024 lines but 3,000 reviews. Your code must read the reviews correctly anyway.
Category Reviews Mean 1-2 starsBooks 397 3.93 18.1%Sports 478 3.90 18.8%Home 504 3.88 19.4%Beauty 442 3.83 19.5%Electronics 591 3.80 20.5%Clothing 588 3.74 21.9%Total 3,000Reviews with a line break in the text: 23import csvfrom collections import Counter, defaultdictfrom statistics import mean
ratings = defaultdict(list)multiline = 0# TODO: read data/reviews.csv with csv.DictReader# TODO: append int(rating) per category; count texts that contain "\n"
def summary(values): """Return (count, mean rating, share of 1- and 2-star reviews).""" # TODO: use a Counter of the ratings
# TODO: build the summary per category, sort by mean rating, print the tableHint 1
Some review texts hold a line break inside quotes. A loop over file.readlines() with split(",") breaks those rows in two. csv.DictReader (with newline="" in open()) keeps them whole.
Hint 2
ratings[row["category"]].append(...) works on the first review of a category too, because a defaultdict(list) creates the empty list. Counter(values)[1] is the number of 1-star reviews.
Hint 3
Sort the items of a dict {category: (count, mean, share)} with key=lambda item: item[1][1] and reverse=True. Format the share with .1%.
Solution
import csvfrom collections import Counter, defaultdictfrom statistics import mean
ratings = defaultdict(list)multiline = 0with open("data/reviews.csv", newline="", encoding="utf-8") as file: for row in csv.DictReader(file): ratings[row["category"]].append(int(row["rating"])) if "\n" in row["text"]: multiline += 1
def summary(values): """Return (count, mean rating, share of 1- and 2-star reviews).""" stars = Counter(values) return len(values), mean(values), (stars[1] + stars[2]) / len(values)
rows = {category: summary(values) for category, values in ratings.items()}ranked = sorted(rows.items(), key=lambda item: item[1][1], reverse=True)
print(f"{'Category':<12} {'Reviews':>7} {'Mean':>5} {'1-2 stars':>9}")for category, (count, avg, low_share) in ranked: print(f"{category:<12} {count:>7,} {avg:>5.2f} {low_share:>9.1%}")total = sum(count for count, _, _ in rows.values())print(f"{'Total':<12} {total:>7,}")print("Reviews with a line break in the text:", multiline)
assert total == 3000assert multiline == 23assert rows["Electronics"][0] == 591Category Reviews Mean 1-2 starsBooks 397 3.93 18.1%Sports 478 3.90 18.8%Home 504 3.88 19.4%Beauty 442 3.83 19.5%Electronics 591 3.80 20.5%Clothing 588 3.74 21.9%Total 3,000Reviews with a line break in the text: 23How it works:
- The CSV parser handles quoted fields, so a review text with a line break stays one value. 3,000 reviews plus 1 header plus 23 extra lines inside texts give the 3,024 lines of the file (module 07).
defaultdict(list)groups the ratings per category in one pass (module 09).int()converts the text"5"into a number before any math (module 01).summary()is a small pure function: it depends only on its argument, so you can test it with a short list (module 05).Counterreturns 0 for a rating that never occurs.- The dict comprehension builds one summary per category (module 04).
sorted()with akeyorders the pairs by the mean. - The format specs
>7,,>5.2fand>9.1%give a thousands separator, two decimals and a percentage (module 02).
Alternative: keep a Counter per category instead of a list, stars[row["category"]][int(row["rating"])] += 1. It uses less memory on a large file, and the mean is sum(r * n for r, n in c.items()) / c.total().
P1-05 · API errors, latency and the worst streak
Section titled “P1-05 · API errors, latency and the worst streak”Write the code: the API lines of data/logs/app.log look like this (the timestamps are in UTC):
2024-05-01 08:08:39,278 INFO [api] 172.16.4.9 POST /api/v1/predict 201 93ms user=mei.chen@example.orgPer hour of the day, count the requests, the client errors (status 4xx) and the server errors (5xx), and compute the error rate and the mean response time. Then print:
- the hour with the highest error rate, in UTC and in Chicago time (the on-call engineer works there);
- the worst streak: the highest number of failed requests among any 20 consecutive API requests, and the time of the last request of that window.
Use a compiled regex with named groups, match-case on the status class (status // 100) and a deque(maxlen=20) for the window.
Hour Requests 4xx 5xx Errors Mean ms08:00 27 1 0 3.7% 61.209:00 32 1 0 3.1% 51.910:00 40 7 0 17.5% 70.811:00 30 5 0 16.7% 64.512:00 23 1 0 4.3% 64.313:00 35 10 0 28.6% 81.414:00 34 6 0 17.6% 61.915:00 44 6 0 13.6% 64.216:00 35 5 0 14.3% 54.917:00 35 3 1 11.4% 100.418:00 29 4 1 17.2% 116.119:00 27 2 1 11.1% 86.5Worst hour: 13:00 UTC, 08:00 CDT in ChicagoWorst 20 requests in a row: 7 failed, ending 13:30:00 UTCimport refrom collections import Counter, dequefrom datetime import UTC, datetimefrom zoneinfo import ZoneInfo
API_LINE = re.compile(r"...") # TODO: named groups stamp, status and msWINDOW = 20requests = Counter()client_errors = Counter()server_errors = Counter()total_ms = Counter()recent = deque(maxlen=WINDOW)# TODO: loop over the lines; skip lines that do not match# TODO: make the timestamp an aware UTC datetime; count per hour# TODO: match status // 100 to count 4xx and 5xx; track the worst window# TODO: print the table, the worst hour in UTC and Chicago, and the worst windowHint 1
Match only [api] lines: \[api\] in the pattern. The timestamp has milliseconds after the comma; capture the part before it and parse it with "%Y-%m-%d %H:%M:%S". .replace(tzinfo=UTC) makes it aware.
Hint 2
match status // 100: with case 4:, case 5: and case _: gives each request a class. Append True for a failed request to the deque. Once it holds 20 items, sum(recent) is the number of failures in the window.
Hint 3
max(requests, key=error_rate) returns the hour with the highest rate, if error_rate(hour) is a function. For Chicago time, build an aware datetime for that hour and call .astimezone(ZoneInfo("America/Chicago")).
Solution
import refrom collections import Counter, dequefrom datetime import UTC, datetimefrom zoneinfo import ZoneInfo
API_LINE = re.compile( r"^(?P<stamp>\S+ \S+),\d{3} \w+ \[api\] \S+ (?P<method>[A-Z]+) \S+ " r"(?P<status>\d{3}) (?P<ms>\d+)ms")WINDOW = 20
requests = Counter()client_errors = Counter()server_errors = Counter()total_ms = Counter()recent = deque(maxlen=WINDOW) # True for each failed request of the last 20worst_window = (0, None)with open("data/logs/app.log", encoding="utf-8") as file: for line in file: found = API_LINE.match(line) if found is None: continue stamp = datetime.strptime(found["stamp"], "%Y-%m-%d %H:%M:%S") stamp = stamp.replace(tzinfo=UTC) hour = stamp.hour requests[hour] += 1 total_ms[hour] += int(found["ms"]) match int(found["status"]) // 100: case 4: client_errors[hour] += 1 failed = True case 5: server_errors[hour] += 1 failed = True case _: failed = False recent.append(failed) if len(recent) == WINDOW and sum(recent) > worst_window[0]: worst_window = (sum(recent), stamp)
def error_rate(hour): """Return the share of failed requests in one hour.""" return (client_errors[hour] + server_errors[hour]) / requests[hour]
print(f"{'Hour':<5} {'Requests':>8} {'4xx':>4} {'5xx':>4} {'Errors':>7} {'Mean ms':>8}")for hour in sorted(requests): print( f"{hour:02d}:00 {requests[hour]:>8} {client_errors[hour]:>4} " f"{server_errors[hour]:>4} {error_rate(hour):>7.1%} " f"{total_ms[hour] / requests[hour]:>8.1f}" )
worst = max(requests, key=error_rate)utc_hour = datetime(2024, 5, 1, worst, tzinfo=UTC)chicago = utc_hour.astimezone(ZoneInfo("America/Chicago"))print(f"Worst hour: {worst:02d}:00 UTC, {chicago:%H:%M %Z} in Chicago")most_failed, end = worst_windowprint( f"Worst {WINDOW} requests in a row: {most_failed} failed, " f"ending {end:%H:%M:%S} UTC")assert requests.total() == 391assert client_errors.total() == 51assert server_errors.total() == 3assert len(recent) == WINDOWHour Requests 4xx 5xx Errors Mean ms08:00 27 1 0 3.7% 61.209:00 32 1 0 3.1% 51.910:00 40 7 0 17.5% 70.811:00 30 5 0 16.7% 64.512:00 23 1 0 4.3% 64.313:00 35 10 0 28.6% 81.414:00 34 6 0 17.6% 61.915:00 44 6 0 13.6% 64.216:00 35 5 0 14.3% 54.917:00 35 3 1 11.4% 100.418:00 29 4 1 17.2% 116.119:00 27 2 1 11.1% 86.5Worst hour: 13:00 UTC, 08:00 CDT in ChicagoWorst 20 requests in a row: 7 failed, ending 13:30:00 UTCHow it works:
- The pattern is compiled once and reused for 500 lines (module 09).
\[api\]escapes the brackets, so only the 391 API lines match. The 8 traceback lines and the 101 other log lines giveNoneand are skipped (module 03). - The variable is called
found, notmatch, so it does not hide thematchstatement that follows.matchcompares the status class with eachcase;case _catches 2xx and 3xx (module 03). - A
Counterreturns 0 for a missing key, so hours without server errors need no special case. 51 client errors and 3 server errors are the totals of the whole log. deque(maxlen=20)drops the oldest item when a new one arrives, so it always holds the last 20 requests (module 09).sum()of booleans counts theTruevalues.- The log is in UTC.
astimezone()converts the worst hour for display only: on 2024-05-01, Chicago is on daylight saving time (CDT, UTC−5), so 13:00 UTC is 08:00 there.
Interpretation: 13:00 is the worst hour, but its 10 errors are all 4xx: 4 bad requests (400), 2 auth failures (401), 2 rate limits (429), a 404 and a 422. Only 3 requests in the whole day failed on the server side, one per hour from 17:00. Those 5xx responses took about 1 to 1.3 s each, which lifts the mean response time of those hours to 87–116 ms. Without the 1,188 ms failure, 17:00 would average about 68 ms. The clients cause most errors; the server causes the latency.
P1-06 · Choose and justify: match log users to customers
Section titled “P1-06 · Choose and justify: match log users to customers”Choose a method and justify it: the support team wants the API requests of data/logs/app.log per subscription plan. The plan is in data/customers.json; the log has only an e-mail address per request (user=..., or user=- for anonymous calls). You can match on the full e-mail address, or on the part before the @ (the local part). Compute both matches, print the names that match only on the local part, then sum the requests per plan with the key you choose. Write one sentence on why you chose it.
Exact e-mail matches: 4 of 8 log usersLocal-part matches: 8 of 8 log usersSame name, other domain: diego.ramos, lucas.martin, mei.chen, tom.beckerRequests by plan (exact matches): basic 46, premium 37, standard 92import jsonimport refrom collections import Counter
# TODO: load the "customers" list of data/customers.json# TODO: count the e-mail addresses in the log with re.findall and Counter
def local_part(email): """Return the part of an e-mail address before the @.""" # TODO
# TODO: build two lookups (by e-mail, by local part) and compare with sets# TODO: sum the requests per plan for the key you chooseHint 1
re.findall(r"user=(\S+@\S+)", text) returns the captured e-mail of every line and skips user=-.
Hint 2
set(log_users) & set(by_email) is the set of e-mail addresses found in both places. Set difference loose - exact gives the extra matches of the looser key.
Solution
import jsonimport refrom collections import Counter
with open("data/customers.json", encoding="utf-8") as file: customers = json.load(file)["customers"]with open("data/logs/app.log", encoding="utf-8") as file: log_users = Counter(re.findall(r"user=(\S+@\S+)", file.read()))
def local_part(email): """Return the part of an e-mail address before the @.""" return email.split("@")[0]
by_email = {c["email"]: c for c in customers}by_local = {local_part(c["email"]): c for c in customers}assert len(by_local) == len(customers), "a local part occurs twice"
exact = set(log_users) & set(by_email)loose = {email for email in log_users if local_part(email) in by_local}review = sorted(local_part(email) for email in loose - exact)
print(f"Exact e-mail matches: {len(exact)} of {len(log_users)} log users")print(f"Local-part matches: {len(loose)} of {len(log_users)} log users")print("Same name, other domain:", ", ".join(review))
per_plan = Counter()for email in exact: per_plan[by_email[email]["plan"]] += log_users[email]print( "Requests by plan (exact matches):", ", ".join(f"{plan} {n}" for plan, n in sorted(per_plan.items())),)assert len(exact) == 4assert len(loose) == 8assert per_plan.total() == 175Exact e-mail matches: 4 of 8 log usersLocal-part matches: 8 of 8 log usersSame name, other domain: diego.ramos, lucas.martin, mei.chen, tom.beckerRequests by plan (exact matches): basic 46, premium 37, standard 92How it works:
json.load()gives a dict; the records are in its"customers"list (module 07).re.findall()with one group returns the captured e-mails, andCountercounts the requests per address (module 09).- Two dict comprehensions build lookups by key (module 04). A dict lookup and a set intersection are fast, whatever the number of customers. A nested loop over log users and customers would compare every pair.
loose - exactis the set of users that match only on the local part. Sorting it makes the printed order stable.per_plan.total()is 46 + 37 + 92 = 175 requests by known customers.
Choice: match on the full e-mail address. It is a unique identifier; the local part is not. mei.chen@example.org in the log and mei.chen@example.com in the customer file can be the same person with a work address, or two different people. A silent join on the local part would add 4 users, and 176 requests, to the wrong plans if the guess is wrong. The code has the same weakness: if two customers shared a local part, the dict comprehension would keep only the last one. The assert after by_local checks that this does not happen in this file. Report the 4 names for a human to check instead.
P1-07 · Refactor: a copy-paste traffic report
Section titled “P1-07 · Refactor: a copy-paste traffic report”Refactor: the starter script prints, for each year of data/web_traffic.csv, the mean daily visits (5 days have a blank visits value), the total signups and the signup rate (signups per unique visitor). It works, but the same block appears three times, the names say nothing and the file is opened without with. Rewrite it with one documented function year_summary(rows, year) and a loop. The output must stay the same.
2022 3512 21255 2.21%2023 4058 24858 2.24%2024 5497 33565 2.22%import csv
f = open("data/web_traffic.csv", encoding="utf-8")rows = list(csv.DictReader(f))f.close()
v = []s = 0u = 0for r in rows: if r["date"][:4] == "2022": if r["visits"] != "": v.append(int(r["visits"])) s = s + int(r["signups"]) u = u + int(r["unique_visitors"])print("2022", round(sum(v) / len(v)), s, str(round(s / u * 100, 2)) + "%")
v = []s = 0u = 0for r in rows: if r["date"][:4] == "2023": if r["visits"] != "": v.append(int(r["visits"])) s = s + int(r["signups"]) u = u + int(r["unique_visitors"])print("2023", round(sum(v) / len(v)), s, str(round(s / u * 100, 2)) + "%")
v = []s = 0u = 0for r in rows: if r["date"][:4] == "2024": if r["visits"] != "": v.append(int(r["visits"])) s = s + int(r["signups"]) u = u + int(r["unique_visitors"])print("2024", round(sum(v) / len(v)), s, str(round(s / u * 100, 2)) + "%")# TODO: replace the three copies with year_summary(rows, year) and a loop# TODO: use with, clear names, comprehensions and a % format specHint 1
The three blocks differ only in the year. That difference becomes the parameter of the function.
Hint 2
Return a dict with three named values instead of printing inside the function. Then the caller decides how to print, and a test can check the numbers.
Hint 3
f"{rate:.2%}" multiplies by 100, rounds and adds the % sign in one step. str(round(x, 2)) drops trailing zeros (2.2 instead of 2.20), so it can change the output.
Solution
import csv
def year_summary(rows, year): """Summarize one year of daily web traffic.
Args: rows: Rows of data/web_traffic.csv as dicts of strings. year: Four-digit year as text, for example "2023".
Returns: A dict with the mean visits (blank days skipped), the total signups and the signup rate (signups per unique visitor). """ days = [row for row in rows if row["date"].startswith(year)] visits = [int(row["visits"]) for row in days if row["visits"]] signups = sum(int(row["signups"]) for row in days) unique = sum(int(row["unique_visitors"]) for row in days) return { "mean_visits": sum(visits) / len(visits), "signups": signups, "signup_rate": signups / unique, }
with open("data/web_traffic.csv", newline="", encoding="utf-8") as file: rows = list(csv.DictReader(file))
summaries = {year: year_summary(rows, year) for year in ("2022", "2023", "2024")}for year, info in summaries.items(): print( year, round(info["mean_visits"]), info["signups"], f"{info['signup_rate']:.2%}", )assert round(summaries["2022"]["mean_visits"]) == 3512assert round(summaries["2024"]["mean_visits"]) == 5497assert summaries["2023"]["signups"] == 248582022 3512 21255 2.21%2023 4058 24858 2.24%2024 5497 33565 2.22%How it works:
with open(...)closes the file even if a line raises an error (module 07).newline=""is the documented way to open a CSV file.- The function takes the only part that changed, the year, as a parameter (module 05). Its docstring says what the rows are and what comes back.
- Three comprehensions replace the accumulator variables (module 04).
if row["visits"]skips the blank strings, because""is falsy (module 03). - The function returns numbers, not text. The caller formats them; the asserts check the yearly values of the original output.
- The dict comprehension over the years replaces the copies. A fourth year is now one more item in the tuple, not 10 more lines.
P1-08 · Interpret: drift or wear?
Section titled “P1-08 · Interpret: drift or wear?”Interpret a result: data/sensors.csv holds 14 days of 10-minute readings from 4 sensors, with the columns timestamp, sensor_id, temperature_c, humidity_pct, vibration_mm_s and status. Some numeric cells are blank. The status column follows this rule:
failif the vibration is at least 11.2 mm/s or the temperature at least 42 °C;- else
warnif the vibration is at least 4.5 mm/s or the temperature at least 33 °C; - else
ok.
Compute, per sensor: the mean temperature on the first and on the last day, the temperature change per day, the median vibration on the first and on the last day, and the count of each status. Count the blank temperatures. Then answer three questions in a short comment:
- Which sensor’s temperature drifts, and by how much per day?
- Why does the
statuscolumn not warn about that sensor? - Which sensor most needs a technician, and is its problem a temperature problem?
Blank temperatures skipped: 22Sensor Temp 1st Temp last Per day Vib 1st Vib last StatusesS1 22.06 22.02 +0.00 2.13 2.09 ok 2002, warn 14S2 24.49 24.32 -0.01 2.70 2.79 fail 5, ok 1994, warn 17S3 21.29 25.85 +0.35 1.88 1.85 ok 1994, warn 22S4 26.04 25.94 -0.01 3.08 8.77 fail 19, ok 1597, warn 400import csvfrom collections import Counter, defaultdictfrom datetime import datetimefrom statistics import mean, median
daily_temp = defaultdict(list) # (sensor, day) -> temperaturesdaily_vib = defaultdict(list) # (sensor, day) -> vibrationsstatuses = defaultdict(Counter) # sensor -> Counter of statusesblanks = 0
def to_float(text): """Return text as a float, or None for a blank cell.""" # TODO
# TODO: read the rows; count the statuses; group the values by (sensor, date)# TODO: print the table; write your three answers as commentsHint 1
A tuple can be a dict key: daily_temp[sensor, day].append(temperature). float("") raises ValueError, so to_float() can return None for a blank cell.
Hint 2
Compare daily values, not two single readings. The temperature has a daily cycle, so a reading at 03:00 and one at 15:00 differ by several degrees on the same day. The change per day is (end - start) / 13 for the 13 days from May 1 to May 14.
Hint 3
The format spec +z7.2f shows the sign and turns a rounded -0.00 into +0.00. For questions 2 and 3, compare the numbers in your table with the thresholds of the status rule.
Solution
import csvfrom collections import Counter, defaultdictfrom datetime import datetimefrom statistics import mean, median
daily_temp = defaultdict(list) # (sensor, day) -> temperaturesdaily_vib = defaultdict(list) # (sensor, day) -> vibrationsstatuses = defaultdict(Counter) # sensor -> Counter of statusesblanks = 0
def to_float(text): """Return text as a float, or None for a blank cell.""" try: return float(text) except ValueError: return None
with open("data/sensors.csv", newline="", encoding="utf-8") as file: for row in csv.DictReader(file): sensor = row["sensor_id"] statuses[sensor][row["status"]] += 1 day = datetime.fromisoformat(row["timestamp"]).date() temperature = to_float(row["temperature_c"]) vibration = to_float(row["vibration_mm_s"]) if temperature is None: blanks += 1 else: daily_temp[sensor, day].append(temperature) if vibration is not None: daily_vib[sensor, day].append(vibration)
first_day = min(day for _, day in daily_temp)last_day = max(day for _, day in daily_temp)span = (last_day - first_day).daysslopes = {}vib_last = {}print(f"Blank temperatures skipped: {blanks}")print( f"{'Sensor':<6} {'Temp 1st':>8} {'Temp last':>9} {'Per day':>7} " f"{'Vib 1st':>7} {'Vib last':>8} Statuses")for sensor in sorted(statuses): start = mean(daily_temp[sensor, first_day]) end = mean(daily_temp[sensor, last_day]) slopes[sensor] = (end - start) / span vib_start = median(daily_vib[sensor, first_day]) vib_last[sensor] = median(daily_vib[sensor, last_day]) counts = ", ".join(f"{k} {v}" for k, v in sorted(statuses[sensor].items())) print( f"{sensor:<6} {start:>8.2f} {end:>9.2f} {slopes[sensor]:>+z7.2f} " f"{vib_start:>7.2f} {vib_last[sensor]:>8.2f} {counts}" )
# 1. S3 drifts: its daily mean rises about 0.35 °C per day (21.29 -> 25.85).# 2. The rule warns only from 33 °C. S3 is still far below it, so a slow# calibration drift never reaches the threshold.# 3. S4: 400 warn and 19 fail. Its temperature is stable, but its median# vibration rose from 3.08 to 8.77 mm/s, above the 4.5 warn threshold.# The alerts come from vibration (wear), not from temperature.assert span == 13assert blanks == 22assert max(slopes, key=slopes.get) == "S3"assert max(vib_last, key=vib_last.get) == "S4"assert statuses["S4"]["warn"] == 400Blank temperatures skipped: 22Sensor Temp 1st Temp last Per day Vib 1st Vib last StatusesS1 22.06 22.02 +0.00 2.13 2.09 ok 2002, warn 14S2 24.49 24.32 -0.01 2.70 2.79 fail 5, ok 1994, warn 17S3 21.29 25.85 +0.35 1.88 1.85 ok 1994, warn 22S4 26.04 25.94 -0.01 3.08 8.77 fail 19, ok 1597, warn 400How it works:
defaultdict(Counter)creates aCounterper sensor on first use, so one line counts the statuses (module 09). The status is counted for every row, also for rows with a blank cell.to_float()keeps thetryblock to the one conversion and returnsNonefor a blank (module 06). The caller testsis None, not truthiness, because0.0would be a valid reading (module 03).datetime.fromisoformat()reads2024-05-01T00:00:00;.date()drops the time, so all readings of a day share one key. Subtracting two dates gives atimedelta;.daysis 13.- The median of the vibration ignores the few spikes; a mean would let one ×5 spike move the daily value.
Interpretation: a threshold rule finds sudden problems, not slow ones. S3’s drift adds about 4.6 °C over two weeks, yet its status stays mostly ok. To catch drift, compare a sensor with its own history or with its neighbors. S4 has the most alerts, and the vibration columns show why: its typical vibration almost tripled on the last day. Check which part of a rule fired before you send a technician to fix the wrong part.
P1-09 · Fix the bugs: conversion by device
Section titled “P1-09 · Fix the bugs: conversion by device”Fix the bugs: data/ab_test.csv holds 10,000 users of a checkout test. The report must show, per group and per device, the conversion rate (buyers per user) and the average order value, AOV (revenue per buyer). The current script shows a conversion rate of 100% everywhere, and its device table lists the groups too:
import csv
def conversion_by(rows, column, counts={}): for row in rows: key = row[column] users, buyers, revenue = counts.get(key, (0, 0, 0.0)) if row["converted"]: buyers += 1 counts[key] = (users + 1, buyers, revenue + float(row["revenue"])) return counts
with open("data/ab_test.csv", newline="", encoding="utf-8") as file: rows = list(csv.DictReader(file))
for column in ["group", "device"]: print(f"By {column}:") for key, (users, buyers, revenue) in sorted(conversion_by(rows, column).items()): print(f" {key:<10} {buyers / users:>6.2%} AOV {revenue / users:>6.2f}")By group: control 100.00% AOV 4.38 treatment 100.00% AOV 4.85By device: control 100.00% AOV 4.38 desktop 100.00% AOV 5.30 mobile 100.00% AOV 4.07 tablet 100.00% AOV 5.28 treatment 100.00% AOV 4.85Find and fix the three bugs so that the script prints:
By group: control 10.12% AOV 43.30 treatment 11.66% AOV 41.54By device: desktop 13.24% AOV 40.05 mobile 9.25% AOV 43.97 tablet 11.96% AOV 44.18import csv
def conversion_by(rows, column, counts={}): for row in rows: key = row[column] users, buyers, revenue = counts.get(key, (0, 0, 0.0)) if row["converted"]: buyers += 1 counts[key] = (users + 1, buyers, revenue + float(row["revenue"])) return counts
with open("data/ab_test.csv", newline="", encoding="utf-8") as file: rows = list(csv.DictReader(file))
for column in ["group", "device"]: print(f"By {column}:") for key, (users, buyers, revenue) in sorted(conversion_by(rows, column).items()): print(f" {key:<10} {buyers / users:>6.2%} AOV {revenue / users:>6.2f}")# TODO: find and fix the three bugsHint 1
Every CSV value is a string. Which strings are falsy? Is "0" one of them?
Hint 2
The device table contains control and treatment. The default value of counts is created once, when Python runs the def line, and every call without a counts argument shares it.
Hint 3
AOV is revenue per buyer. Revenue per user is a different metric: it mixes the conversion rate and the order value.
Solution
import csv
def conversion_by(rows, column): """Return {value of column: (users, buyers, revenue)} for A/B test rows.""" counts = {} for row in rows: key = row[column] users, buyers, revenue = counts.get(key, (0, 0, 0.0)) if int(row["converted"]) == 1: buyers += 1 counts[key] = (users + 1, buyers, revenue + float(row["revenue"])) return counts
with open("data/ab_test.csv", newline="", encoding="utf-8") as file: rows = list(csv.DictReader(file))
results = {}for column in ["group", "device"]: results[column] = conversion_by(rows, column) print(f"By {column}:") for key, (users, buyers, revenue) in sorted(results[column].items()): print(f" {key:<10} {buyers / users:>6.2%} AOV {revenue / buyers:>6.2f}")
assert sum(users for users, _, _ in results["group"].values()) == 10_000assert sum(users for users, _, _ in results["device"].values()) == 10_000users, buyers, _ = results["group"]["treatment"]assert round(buyers / users, 4) == 0.1166By group: control 10.12% AOV 43.30 treatment 11.66% AOV 41.54By device: desktop 13.24% AOV 40.05 mobile 9.25% AOV 43.97 tablet 11.96% AOV 44.18How it works:
- Bug 1, the mutable default.
counts={}is evaluated once. The second call (fordevice) kept adding to the dict of the first call, so the group rows leaked into the device table (module 05). A new dict inside the function fixes it. - Bug 2, a string in a truth test.
row["converted"]is"0"or"1". Both are non-empty strings, so both are truthy, and every user counted as a buyer (modules 01 and 07). Convert first:int(row["converted"]) == 1. - Bug 3, the wrong denominator.
revenue / usersis revenue per user (4.38 and 4.85). AOV divides by the buyers. - The asserts check that each table covers all 10,000 users exactly once. That check would have caught bug 1 at once: the buggy device table holds 20,000 users.
Interpretation: in this sample, treatment converts better (11.66% against 10.12%), but its buyers spend about the same per order. Whether the gap is real or noise is a statistics question for module 29. The extra revenue of the treatment comes from more buyers, not bigger orders. If a group had no buyer, revenue / buyers would raise ZeroDivisionError; a production report would print n/a for that row.
P1-10 · A command-line log filter
Section titled “P1-10 · A command-line log filter”Write the code: build a script log_query.py that filters the normal lines of a log file and counts the kept lines per component. Use argparse:
- a positional
logfile; --levelwith the choicesDEBUG,INFO,WARNING,ERROR(defaultINFO): keep this level and the levels above it;--component NAME: keep only one component;--between START END: two clock timesHH:MM, parsed by your owntype=function. A bad time such as25:00must give a clear argparse error; aSTARTafterENDtoo;--show N: also print the first N kept lines, with the message shortened to 60 characters. N must be 1 or more;--show -5must give an argparse error, not a silent slice.
Put the work in main(argv=None), which returns the number of kept lines, under a main guard, so that another script can import it. Running python log_query.py data/logs/app.log --level WARNING --between 12:00 15:00 prints:
Matched 6 of 492 log lines api 4 validator 2import argparseimport refrom collections import Counterfrom datetime import datetime, time
LINE = re.compile(r"...") # TODO: groups stamp, level, component, messageLEVELS = {"DEBUG": 10, "INFO": 20, "WARNING": 30, "ERROR": 40}
def clock_time(text): """Parse HH:MM for argparse, with a clear message for bad input.""" # TODO: strptime(text, "%H:%M").time(); raise argparse.ArgumentTypeError
def positive_int(text): """Parse a count of 1 or more for argparse.""" # TODO
def parse_line(line): """Return the fields of a normal log line, or None for other lines.""" # TODO
def main(argv=None): parser = argparse.ArgumentParser(description="Filter and count log lines.") # TODO: add the five arguments, parse argv, check START <= END # TODO: read the file, filter, count with Counter, print, return the count
# TODO: main guardHint 1
nargs=2 with type=clock_time calls your function once per value and gives a list of two time objects. metavar=("START", "END") names them in --help.
Hint 2
A type= function signals bad input with raise argparse.ArgumentTypeError(...). For a rule that involves two arguments, call parser.error("...") after parsing. Both print the usage and exit with code 2.
Hint 3
Compare levels by number: LEVELS[record["level"]] < LEVELS[args.level] means “too low, skip”. Without --between, use the full day: time.min to time.max.
Solution
"""log_query.py: filter and count the lines of an application log."""
import argparseimport reimport textwrapfrom collections import Counterfrom datetime import datetime, time
LINE = re.compile( r"^(?P<stamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}),\d{3} " r"(?P<level>\w+) \[(?P<component>\w+)\] (?P<message>.*)$")LEVELS = {"DEBUG": 10, "INFO": 20, "WARNING": 30, "ERROR": 40}
def clock_time(text): """Parse HH:MM for argparse, with a clear message for bad input.""" try: return datetime.strptime(text, "%H:%M").time() except ValueError: raise argparse.ArgumentTypeError( f"invalid time {text!r}, use HH:MM such as 09:30" ) from None
def positive_int(text): """Parse a count of 1 or more for argparse.""" try: value = int(text) except ValueError: value = 0 if value < 1: raise argparse.ArgumentTypeError(f"invalid count {text!r}, use 1 or more") return value
def parse_line(line): """Return the fields of a normal log line, or None for other lines.""" match = LINE.match(line) if match is None: return None record = match.groupdict() record["stamp"] = datetime.strptime(record["stamp"], "%Y-%m-%d %H:%M:%S") return record
def build_parser(): """Return the argument parser of the command.""" parser = argparse.ArgumentParser(description="Filter and count log lines.") parser.add_argument("logfile", help="path of the log file") parser.add_argument( "--level", choices=LEVELS, default="INFO", help="minimum level (INFO)" ) parser.add_argument("--component", help="keep only this component") parser.add_argument( "--between", nargs=2, type=clock_time, metavar=("START", "END"), help="keep lines from START to END (HH:MM)", ) parser.add_argument( "--show", type=positive_int, metavar="N", help="print the first N lines" ) return parser
def main(argv=None): """Run the command; return the number of kept lines.""" parser = build_parser() args = parser.parse_args(argv) start, end = args.between or (time.min, time.max) if start > end: parser.error("--between: START must not be after END")
total = 0 kept = [] with open(args.logfile, encoding="utf-8") as file: for line in file: record = parse_line(line) if record is None: continue total += 1 if LEVELS[record["level"]] < LEVELS[args.level]: continue if args.component and record["component"] != args.component: continue if start <= record["stamp"].time() <= end: kept.append(record)
print(f"Matched {len(kept)} of {total} log lines") for component, count in Counter(r["component"] for r in kept).most_common(): print(f" {component:<10} {count:>4}") for record in kept[: args.show or 0]: message = textwrap.shorten(record["message"], width=60, placeholder=" ...") print( f"{record['stamp']:%H:%M:%S} {record['level']:<7} " f"[{record['component']}] {message}" ) return len(kept)
if __name__ == "__main__": main()Matched 6 of 492 log lines api 4 validator 2More runs: errors with the first three lines, a bad time, a reversed window and a negative count (tail -n 1 keeps only the error line). 2>&1 sends the error messages to the same place as the normal output, so they appear in order. $? is the exit code of the last command.
python log_query.py data/logs/app.log --level ERROR --show 3python log_query.py data/logs/app.log --between 12:00 25:00 2>&1echo "exit code: $?"python log_query.py data/logs/app.log --between 15:00 12:00 2>&1echo "exit code: $?"python log_query.py data/logs/app.log --level ERROR --show -5 2>&1 | tail -n 1Matched 7 of 492 log lines api 3 db 2 loader 210:37:08 ERROR [db] OperationalError: database is locked (attempt 1/3), ...10:53:55 ERROR [db] OperationalError: database is locked (attempt 1/3), ...10:53:56 ERROR [loader] Failed to parse data/reports/2024-04.csvusage: log_query.py [-h] [--level {DEBUG,INFO,WARNING,ERROR}] [--component COMPONENT] [--between START END] [--show N] logfilelog_query.py: error: argument --between: invalid time '25:00', use HH:MM such as 09:30exit code: 2usage: log_query.py [-h] [--level {DEBUG,INFO,WARNING,ERROR}] [--component COMPONENT] [--between START END] [--show N] logfilelog_query.py: error: --between: START must not be after ENDexit code: 2log_query.py: error: argument --show: invalid count '-5', use 1 or moreThe script also works as a module. Run this from the folder that holds log_query.py:
from log_query import main
kept = main(["data/logs/app.log", "--level", "ERROR", "--component", "api"])assert kept == 3assert main(["data/logs/app.log", "--component", "loader"]) == 29Matched 3 of 492 log lines api 3Matched 29 of 492 log lines loader 29How it works:
parse_line()matches the 492 normal lines and returnsNonefor the 8 traceback lines, which the loop skips (modules 03 and 09).groupdict()turns the named groups into a dict.clock_time()converts theValueErrorofstrptime()into anArgumentTypeError. argparse catches it and prints the usage and your message.from Nonehides the original traceback, because the user needs the message, not the internals (module 06).choices=LEVELSaccepts the keys of the dict, and--helplists them. The rule “START not after END” involves two values, so it is checked after parsing withparser.error(). Both errors exit with code 2 (module 08).main(argv=None)readssys.argvwhen the script runs from the terminal, and the given list when a test or another script calls it. The main guard keepsmain()from running on import.positive_int()rejects0,-5andabcfor--show. Without it,type=intaccepts-5, andkept[:-5]would silently drop the last five lines instead of printing five. Without--show,args.showisNone, andor 0turns it into an empty slice.textwrap.shorten()cuts long messages at a word boundary and adds..., so every printed line stays short.
P1-11 · Monthly revenue from the raw sales file
Section titled “P1-11 · Monthly revenue from the raw sales file”Write the code: data/sales_raw.csv has 1,200 rows, of which 36 are exact copies of an earlier row. Its order_date column mixes three formats: 2023-01-07, 07/01/2023 (day first: 7 January) and January 7, 2023. The formats are listed in data/config.json under cleaning.date_formats. The revenue column is clean.
- Write
parse_date(text, formats). It tries each format and raises aValueErrorthat names the text when none fits. - Many rows share a date. Wrap the parser with
functools.partial(to fix the formats) andfunctools.cache(to parse each distinct text once). - Drop the duplicates and sum
revenueper month. - Write
output/monthly_revenue_raw.csvwith the columnsmonth,revenue, read it back and print a summary. - Use
itertools.accumulateto find the first month in which the running total passes 100,000. - Print the cache statistics, then the error message for the date
2024/01/07.
Unique rows: 1164, duplicates dropped: 36Wrote 24 months to output/monthly_revenue_raw.csvTop months: 2024-12 17,574.71, 2023-12 17,512.38, 2024-11 15,926.52Total revenue: 195,662.50Running total passes 100,000.00 in 2024-03Date cache: 343 hits, 821 missesRejected: date '2024/01/07' matches none of ('%Y-%m-%d', '%d/%m/%Y', '%B %d, %Y')import csvimport jsonfrom collections import defaultdictfrom datetime import datetimefrom functools import cache, partialfrom itertools import accumulatefrom pathlib import Path
def parse_date(text, formats): """Parse text with the first matching format; raise ValueError if none fits.""" # TODO: try each format with datetime.strptime; return a date
# TODO: load the date formats as a tuple; build parse = cache(partial(...))# TODO: read data/sales_raw.csv, skip rows already seen, sum revenue per "YYYY-MM"# TODO: write output/monthly_revenue_raw.csv with csv.DictWriter, read it back# TODO: print the summary, the running-total month, the cache info, the errorHint 1
An exact duplicate has the same values in every column. tuple(row.values()) is hashable, so a set of these tuples remembers the rows you have seen.
Hint 2
Inside the loop over the formats, except ValueError: continue moves on to the next format. Raise only after the loop. cache needs hashable arguments, so pass the formats as a tuple, not a list.
Hint 3
f"{day:%Y-%m}" gives the month key. accumulate(values) yields the running totals; zip() pairs them with the sorted months, and next() with a generator expression returns the first month that passes the limit.
Solution
import csvimport jsonfrom collections import defaultdictfrom datetime import datetimefrom functools import cache, partialfrom itertools import accumulatefrom pathlib import Path
def parse_date(text, formats): """Parse text with the first matching format; raise ValueError if none fits.""" for fmt in formats: try: return datetime.strptime(text.strip(), fmt).date() except ValueError: continue raise ValueError(f"date {text!r} matches none of {formats}")
with open("data/config.json", encoding="utf-8") as file: config = json.load(file)formats = tuple(config["cleaning"]["date_formats"])parse = cache(partial(parse_date, formats=formats))
seen = set()duplicates = 0monthly = defaultdict(float)with open("data/sales_raw.csv", newline="", encoding="utf-8") as file: for row in csv.DictReader(file): key = tuple(row.values()) if key in seen: duplicates += 1 continue seen.add(key) day = parse(row["order_date"]) monthly[f"{day:%Y-%m}"] += float(row["revenue"])
out_dir = Path("output")out_dir.mkdir(parents=True, exist_ok=True)out_path = out_dir / "monthly_revenue_raw.csv"with open(out_path, "w", newline="", encoding="utf-8") as file: writer = csv.DictWriter(file, fieldnames=["month", "revenue"]) writer.writeheader() for month in sorted(monthly): writer.writerow({"month": month, "revenue": f"{monthly[month]:.2f}"})
with open(out_path, newline="", encoding="utf-8") as file: saved = list(csv.DictReader(file))
top = sorted(monthly.items(), key=lambda item: item[1], reverse=True)[:3]print(f"Unique rows: {len(seen)}, duplicates dropped: {duplicates}")print(f"Wrote {len(saved)} months to {out_path.as_posix()}")print("Top months:", ", ".join(f"{m} {v:,.2f}" for m, v in top))print(f"Total revenue: {sum(monthly.values()):,.2f}")
months = sorted(monthly)running = accumulate(monthly[month] for month in months)passed = next(m for m, total in zip(months, running, strict=True) if total > 100_000)print(f"Running total passes 100,000.00 in {passed}")info = parse.cache_info()print(f"Date cache: {info.hits} hits, {info.misses} misses")
try: parse_date("2024/01/07", formats)except ValueError as err: print("Rejected:", err)
assert duplicates == 36assert len(seen) == 1164assert len(saved) == 24assert saved[0]["month"] == "2023-01"assert info.hits + info.misses == len(seen)assert parse("January 7, 2023") == parse("07/01/2023")Unique rows: 1164, duplicates dropped: 36Wrote 24 months to output/monthly_revenue_raw.csvTop months: 2024-12 17,574.71, 2023-12 17,512.38, 2024-11 15,926.52Total revenue: 195,662.50Running total passes 100,000.00 in 2024-03Date cache: 343 hits, 821 missesRejected: date '2024/01/07' matches none of ('%Y-%m-%d', '%d/%m/%Y', '%B %d, %Y')How it works:
- The formats come from the config, not from the code (module 07). When the export changes, you edit one JSON file.
parse_date()returns at the first format that works. Its error message names the text and the formats, so the person who reads it knows what to fix (module 06).partial()fixes theformatsargument, andcache()stores each result by its text (module 09). 1,164 rows have only 821 distinct date texts, so 343 parses are skipped. The checkhits + misses == 1164proves that every unique row went through the cache once.- The set of row tuples finds exact duplicates in one pass, with an average membership test per row (module 04). The duplicate check runs before the date parsing, so a duplicate is never parsed.
accumulate()is lazy;next()stops at the first month that passes the limit, so the rest is never summed.zip(..., strict=True)would raise if the two sequences had different lengths.- Reading the file back checks what is really on disk: 24 rows, starting with January 2023.
as_posix()prints the path with/on every operating system.
Order matters: %d/%m/%Y reads 07/01/2023 as 7 January, which is what the export means. If the list held %m/%d/%Y before it, the same text would parse without an error as 1 July. A date parser that accepts several formats is only as correct as the order of its formats.
P1-12 · Predict the output: scopes, copies and finally
Section titled “P1-12 · Predict the output: scopes, copies and finally”Predict the output: this script combines eight rules from Part 1. Write down what each print() shows, in the order the lines appear, then run it.
Acceptance criteria:
- Write your prediction for all 10 output lines before you run the code. Watch the order of the lines.
- Your prediction matches the Output in the solution, line by line.
- For each wrong line, you can name the rule and the module that explains it.
from collections import Counter
threshold = 30
def is_hot(temperature): return temperature > threshold
threshold = 35print(is_hot(32))
def make_counter(start=0): count = start
def bump(step=1): nonlocal count count += step return count
return bump
bump = make_counter(10)bump()print(bump(5))
rules = [lambda t: t > limit for limit in (30, 40)]print([rule(35) for rule in rules])
row = {"sensor": "S1", "flags": ["drift"]}copy_row = dict(row)copy_row["sensor"] = "S2"copy_row["flags"].append("spike")print(row)
def parse(text): try: return float(text) except ValueError: return None finally: print("checked", repr(text))
print(parse("2.5"), parse("n/a"))
units, boxes = 25, 0while units > 0: units -= 12 boxes += 1print(boxes, units)
for sensor in ["S1", "S2"]: if sensor == "S9": breakelse: print("S9 not found")
statuses = ["ok", "warn", "ok", "fail", "warn", "ok"]print(Counter(statuses).most_common(2))# TODO: write your prediction for each output line before you run itHint 1
A function looks up a name when it runs, not when it is defined. That holds for a global name and for the loop variable that a lambda uses.
Hint 2
dict(row) is a shallow copy: a new dict whose values are the same objects. Python evaluates all arguments of print() before it prints anything.
Hint 3
Trace the while loop on paper: write units and boxes after each pass, and check the condition before the next one.
Solution
from collections import Counter
threshold = 30
def is_hot(temperature): return temperature > threshold
threshold = 35print(is_hot(32))
def make_counter(start=0): count = start
def bump(step=1): nonlocal count count += step return count
return bump
bump = make_counter(10)bump()print(bump(5))
rules = [lambda t: t > limit for limit in (30, 40)]print([rule(35) for rule in rules])
row = {"sensor": "S1", "flags": ["drift"]}copy_row = dict(row)copy_row["sensor"] = "S2"copy_row["flags"].append("spike")print(row)
def parse(text): try: return float(text) except ValueError: return None finally: print("checked", repr(text))
print(parse("2.5"), parse("n/a"))
units, boxes = 25, 0while units > 0: units -= 12 boxes += 1print(boxes, units)
for sensor in ["S1", "S2"]: if sensor == "S9": breakelse: print("S9 not found")
statuses = ["ok", "warn", "ok", "fail", "warn", "ok"]print(Counter(statuses).most_common(2))assert rules[0](35) is Falseassert row["flags"] == ["drift", "spike"]assert row["sensor"] == "S1"assert (boxes, units) == (3, -11)False16[False, False]{'sensor': 'S1', 'flags': ['drift', 'spike']}checked '2.5'checked 'n/a'2.5 None3 -11S9 not found[('ok', 3), ('warn', 2)]How it works:
is_hot()reads the globalthresholdat call time. The call comes afterthreshold = 35, so32 > 35isFalse(module 05, LEGB rule).nonlocal countletsbump()change the variable ofmake_counter(). The first call makes it 11, the second adds 5: 16.- Both lambdas look up
limitwhen they are called. By then the comprehension has finished andlimitis 40, so both test35 > 40. Bind the value at creation time with a default,lambda t, limit=limit: t > limit, to get[True, False](module 05). dict(row)copies one level. The new dict has its own"sensor"key, sorow["sensor"]stays"S1", but both dicts share the oneflagslist (module 04).finallyruns on every exit from thetry, even afterreturn. Python evaluates bothparse()calls first, so bothcheckedlines come before the line with the results (module 06).- The
whileloop runs whileunits > 0: 25, 13, 1, then −11. It makes 3 passes, andunitsends below zero because the loop subtracts a full box each time (module 03). The real count of boxes for 25 units is-(-25 // 12), also 3. - The
forloop never hitsbreak, so itselseruns: the “not found” case of a search (module 03). most_common(2)sorts by count.okhas 3 andwarn2;fail(1) is cut (module 09).
P1-13 · Load a folder of extracts, log the bad files
Section titled “P1-13 · Load a folder of extracts, log the bad files”Write the code: data/reports/ holds six monthly CSV extracts. A colleague also dropped data/legacy_latin1.csv (a supplier list in latin-1 encoding, with other columns) into the job. Load every file with the columns order_id, order_date and revenue, and skip the others with a logged error instead of a crash.
- Define
ExtractErrorand two subclasses:EncodingProblemandMissingColumns. load_extract(path, *, required=REQUIRED, encoding="utf-8")returns anamedtupleExtract(name, rows, revenue). It raisesEncodingProblem(chained to theUnicodeDecodeError) orMissingColumns. The options are keyword-only.load_all(*paths, **options)loads any number of files, forwards the options, logs each result and returns the good extracts.- Log to standard output with the format
%(levelname)-7s %(name)s: %(message)s.
Call load_all() on the sorted reports plus the legacy file. Then try the legacy file again with encoding="latin-1".
INFO extracts: 2024-01.csv: 48 rows, revenue 14162.33INFO extracts: 2024-02.csv: 48 rows, revenue 4719.04INFO extracts: 2024-03.csv: 47 rows, revenue 12296.72INFO extracts: 2024-04.csv: 52 rows, revenue 10879.04INFO extracts: 2024-05.csv: 47 rows, revenue 6675.86INFO extracts: 2024-06.csv: 55 rows, revenue 8533.40ERROR extracts: skipped: legacy_latin1.csv is not utf-8: invalid continuation byteERROR extracts: skipped: legacy_latin1.csv: no column ['order_date', 'order_id', 'revenue']6 extracts, 297 rows, 57,266.39import csvimport loggingimport sysfrom collections import namedtuplefrom pathlib import Path
# TODO: logging.basicConfig(...) to sys.stdout; log = logging.getLogger("extracts")REQUIRED = ("order_id", "order_date", "revenue")Extract = namedtuple("Extract", ["name", "rows", "revenue"])
# TODO: ExtractError, EncodingProblem, MissingColumns
def load_extract(path, *, required=REQUIRED, encoding="utf-8"): """Read one extract and return its name, row count and revenue.""" # TODO
def load_all(*paths, **options): """Load every readable extract; log and skip the others.""" # TODO
# TODO: glob data/reports/*.csv, add the legacy file, print the summary lineHint 1
csv.DictReader(file).fieldnames is the header. set(required) - set(fieldnames) is the set of missing columns. Reading the header already decodes bytes, so keep it inside the try that catches UnicodeDecodeError.
Hint 2
raise EncodingProblem(...) from err keeps the original error as the cause. except ExtractError in load_all() catches both subclasses.
Hint 3
load_all(*paths, Path("data/legacy_latin1.csv")) unpacks the list and adds one more path. load_extract(path, **options) forwards encoding="latin-1" by name. Pass force=True to basicConfig() if logging was configured before.
Solution
import csvimport loggingimport sysfrom collections import namedtuplefrom pathlib import Path
logging.basicConfig( stream=sys.stdout, level=logging.INFO, format="%(levelname)-7s %(name)s: %(message)s", force=True,)log = logging.getLogger("extracts")
REQUIRED = ("order_id", "order_date", "revenue")Extract = namedtuple("Extract", ["name", "rows", "revenue"])
class ExtractError(Exception): """Base class for problems with one extract file."""
class EncodingProblem(ExtractError): """The file is not in the expected text encoding."""
class MissingColumns(ExtractError): """The header lacks a required column."""
def load_extract(path, *, required=REQUIRED, encoding="utf-8"): """Read one extract and return its name, row count and revenue.
Args: path: Path of a CSV file. required: Columns that must be in the header. encoding: Text encoding of the file.
Returns: An Extract named tuple.
Raises: EncodingProblem: If the bytes do not decode with the encoding. MissingColumns: If a required column is missing. """ try: with open(path, newline="", encoding=encoding) as file: reader = csv.DictReader(file) missing = set(required) - set(reader.fieldnames or []) if missing: raise MissingColumns(f"{path.name}: no column {sorted(missing)}") rows = list(reader) except UnicodeDecodeError as err: raise EncodingProblem(f"{path.name} is not {encoding}: {err.reason}") from err return Extract(path.name, len(rows), sum(float(row["revenue"]) for row in rows))
def load_all(*paths, **options): """Load every readable extract; log and skip the others.""" extracts = [] for path in paths: try: extract = load_extract(path, **options) except ExtractError as err: log.error("skipped: %s", err) continue log.info( "%s: %d rows, revenue %.2f", extract.name, extract.rows, extract.revenue ) extracts.append(extract) return extracts
paths = sorted(Path("data/reports").glob("*.csv"))extracts = load_all(*paths, Path("data/legacy_latin1.csv"))retry = load_all(Path("data/legacy_latin1.csv"), encoding="latin-1")total = sum(extract.revenue for extract in extracts)print(f"{len(extracts)} extracts, {sum(e.rows for e in extracts)} rows, {total:,.2f}")assert len(extracts) == 6assert retry == []assert round(total, 2) == 57266.39INFO extracts: 2024-01.csv: 48 rows, revenue 14162.33INFO extracts: 2024-02.csv: 48 rows, revenue 4719.04INFO extracts: 2024-03.csv: 47 rows, revenue 12296.72INFO extracts: 2024-04.csv: 52 rows, revenue 10879.04INFO extracts: 2024-05.csv: 47 rows, revenue 6675.86INFO extracts: 2024-06.csv: 55 rows, revenue 8533.40ERROR extracts: skipped: legacy_latin1.csv is not utf-8: invalid continuation byteERROR extracts: skipped: legacy_latin1.csv: no column ['order_date', 'order_id', 'revenue']6 extracts, 297 rows, 57,266.39How it works:
Path("data/reports").glob("*.csv")finds the extracts;sorted()fixes their order, becauseglob()returns files in no set order (module 07).DictReaderreads by column name, so the different column order of2024-04.csvdoes no harm. The header check happens before any row is read.- Reading latin-1 bytes as UTF-8 raises
UnicodeDecodeError(module 02).load_extract()turns it into anEncodingProblemwith the file name and chains it withfrom err, so the low-level cause stays available in a traceback (module 06). - With the right encoding, the legacy file decodes, but its header has none of the three columns. That is a different problem with a different fix, so it has its own exception class.
- The
*in the signature makesrequiredandencodingkeyword-only, so a call cannot swap them by position.*pathscollects any number of files, and**optionsforwards the keyword options unchanged (module 05). log.error()andlog.info()add a level and the logger name to each line.%s-style arguments are formatted only when the message is really written.
P1-14 · Read a traceback: the merge that stops in April
Section titled “P1-14 · Read a traceback: the merge that stops in April”Fix the bug: merge_reports.py prints the units and revenue of each monthly extract in data/reports/. It stops after March with a traceback. Python 3.13 marks the failing expression with ~ and ^; older versions show the markers differently:
"""merge_reports.py: total units and revenue of the monthly extracts."""
import csvfrom pathlib import Path
COLUMNS = [ "order_id", "order_date", "store_id", "product", "category", "quantity", "revenue"]
def read_rows(path): """Return the rows of one extract as dicts.""" with open(path, newline="", encoding="utf-8") as file: reader = csv.reader(file) next(reader) # skip the header return [dict(zip(COLUMNS, row, strict=True)) for row in reader]
def to_numbers(row): """Convert the numeric fields of one row.""" return int(row["quantity"]), float(row["revenue"])
def month_totals(path): """Return (units, revenue) of one extract.""" units = revenue = 0 for row in read_rows(path): quantity, amount = to_numbers(row) units += quantity revenue += amount return units, revenue
def main(): for path in sorted(Path("data/reports").glob("*.csv")): units, revenue = month_totals(path) print(f"{path.name}: {units} units, {revenue:,.2f}")
if __name__ == "__main__": main()2024-01.csv: 65 units, 14,162.332024-02.csv: 73 units, 4,719.042024-03.csv: 65 units, 12,296.72Traceback (most recent call last): File "/path/to/my-course/merge_reports.py", line 41, in <module> main() ~~~~^^ File "/path/to/my-course/merge_reports.py", line 36, in main units, revenue = month_totals(path) ~~~~~~~~~~~~^^^^^^ File "/path/to/my-course/merge_reports.py", line 28, in month_totals quantity, amount = to_numbers(row) ~~~~~~~~~~^^^^^ File "/path/to/my-course/merge_reports.py", line 21, in to_numbers return int(row["quantity"]), float(row["revenue"]) ~~~^^^^^^^^^^^^^^^^^ValueError: invalid literal for int() with base 10: '238.0'Read the traceback from the bottom up and answer: what failed, in which function, which file was being read, and in which function did the bad value enter? Then fix the script so that it prints all six months. Keep the four functions.
2024-01.csv: 65 units, 14,162.332024-02.csv: 73 units, 4,719.042024-03.csv: 65 units, 12,296.722024-04.csv: 75 units, 10,879.042024-05.csv: 65 units, 6,675.862024-06.csv: 66 units, 8,533.40# TODO: answer the four questions as comments, then fix merge_reports.py# What failed:# In which function:# Which file:# Where the bad value entered:Hint 1
The last line says what failed: int() got the text '238.0'. Is that a quantity? The last frame says where. The printed lines above the traceback say which file was next.
Hint 2
Look at the header of data/reports/2024-04.csv. read_rows() skips the header and pairs every row with the fixed list COLUMNS. What happens when a file has the same columns in another order?
Solution
- What failed:
int()raisedValueErroron'238.0', a revenue value, not a quantity. - In which function:
to_numbers(), the last frame. It is not the bug; it received a wrong value. - Which file: the output stops after
2024-03.csv, and the files are sorted, so the failing file is2024-04.csv. - Where the bad value entered: in
read_rows(). It throws the header away and assumes the column order ofCOLUMNS.2024-04.csvhas the orderorder_date, order_id, store_id, category, product, revenue, quantity, sozip()labels the revenue asquantity.strict=Truedid not help: the number of columns is right, only the order differs.
The fix pairs each row with the file’s own header:
import csvfrom pathlib import Path
def read_rows(path): """Return the rows of one extract as dicts keyed by its own header.""" with open(path, newline="", encoding="utf-8") as file: reader = csv.reader(file) header = next(reader) return [dict(zip(header, row, strict=True)) for row in reader]
def to_numbers(row): """Convert the numeric fields of one row.""" return int(row["quantity"]), float(row["revenue"])
def month_totals(path): """Return (units, revenue) of one extract.""" units = revenue = 0 for row in read_rows(path): quantity, amount = to_numbers(row) units += quantity revenue += amount return units, revenue
totals = {}for path in sorted(Path("data/reports").glob("*.csv")): totals[path.name] = month_totals(path) units, revenue = totals[path.name] print(f"{path.name}: {units} units, {revenue:,.2f}")
assert len(totals) == 6assert round(totals["2024-04.csv"][1], 2) == 10879.042024-01.csv: 65 units, 14,162.332024-02.csv: 73 units, 4,719.042024-03.csv: 65 units, 12,296.722024-04.csv: 75 units, 10,879.042024-05.csv: 65 units, 6,675.862024-06.csv: 66 units, 8,533.40How it works:
- A traceback lists the calls from the outside in:
<module>,main(),month_totals(),to_numbers(). Python raised the error in the last frame, but the frames above show how the value got there (module 06). zip(header, row, strict=True)pairs each value with the name in the same position of the file’s own header, and raises if a row has a different length (module 03).csv.DictReaderdoes the same in one step (module 07).- Without the fix,
2024-01.csvto2024-03.csvprinted correct totals only because their column order happened to matchCOLUMNS. The worst case is a swap that does not crash: two text columns in another order give wrong results in silence. Read columns by name. - The asserts check that all six months are present and that April’s revenue matches the sum of its
revenuecolumn.
Self-assessment rubric
Section titled “Self-assessment rubric”Rate yourself on each skill after you finish the exercises. Base the rating on what you did without the solution. The last column names the exercises that test the skill.
| Skill area | Not yet | Getting there | Ready | Tested in |
|---|---|---|---|---|
| 01. Basics: types, operators, conversion | You guess what /, // and int() give. |
You get the results right, but check falsy values by trial. | You predict types, division results and truthiness, and convert CSV text before you compute. | P1-01, P1-09 |
| 02. Strings: cleaning, f-strings, encodings | You build report lines by concatenation. | You use f-strings, but the table columns do not line up. | You align report tables with format specs and explain a UnicodeDecodeError. |
P1-01, P1-03, P1-04, P1-13 |
| 03. Control flow: branches and loops | Your loops use indexes and flags. | You loop and branch correctly, but miss the edge cases. | You use match-case, while, zip() and loop else, and skip bad lines with continue. |
P1-05, P1-12, P1-14 |
| 04. Data structures: list, tuple, dict, set | You use lists for every job. | You use dicts and sets, but copies surprise you. | You pick the structure by the operation, use tuples as keys and explain shallow copies. | P1-06, P1-08, P1-11, P1-12 |
| 05. Functions: parameters, scope, closures | You copy code instead of writing a function. | You write functions, but print inside them or use mutable defaults. | You write documented functions with keyword-only options, *args and **kwargs, and predict scope and closures. |
P1-07, P1-09, P1-12, P1-13 |
| 06. Errors: exceptions, logging, tracebacks | You use bare except: or let the script crash. |
You catch errors, but the try blocks are big or the messages vague. |
You catch specific exceptions, define and chain your own, log problems and find a bug from a traceback. | P1-02, P1-11, P1-13, P1-14 |
| 07. Files: paths, CSV, JSON | You split CSV lines with split(","). |
You use csv and json, but forget newline="" or the encoding. |
You read and write CSV, JSON and text files, process a folder with glob() and write only to output/. |
P1-04, P1-06, P1-11, P1-13 |
| 08. Modules: scripts and CLIs | Your scripts run only with hard-coded values. | You write an argparse CLI, but cannot import it into another script. | You build a CLI with types, choices and clear errors, behind a main guard, and import its main(). |
P1-10 |
| 09. Standard library: collections, functools, itertools, datetime, regex | You count with plain dicts and parse dates by slicing. | You use Counter and strptime, but write fragile regex patterns. |
You combine Counter, defaultdict, deque, namedtuple, cache, accumulate, zoneinfo and named-group regex. |
P1-03, P1-05, P1-08, P1-11, P1-13 |
This checkpoint does not test recursion, map/filter, pickle, packages and pyproject.toml, virtual environments, or os, sys and subprocess. Check those with the self-check questions of modules 05, 07, 08 and 09.
You are ready for Part 2 when you can:
- Solve at least 10 of the 14 exercises without opening the solution, including one challenge.
- Predict the output of P1-01 and P1-12 with at most one wrong line each.
- Read a CSV, JSON or log file, or a folder of them, clean the values and handle bad lines without crashing.
- Group and count records with dicts, sets,
Counteranddefaultdict, and explain your choice of structure. - Split a script into small documented functions without changing its output.
- Catch only the exceptions you expect, raise errors whose message says what to fix, and log the problems.
- Read a traceback from the bottom up and find the function where the bad value entered.
- Parse dates and times, convert them between time zones, and extract fields from text with a regular expression.
- Write a command-line script with argparse that another script can import.
Rated “Not yet” in a row? Review that module’s lesson and cheat sheet, redo two of its core exercises, then try the matching checkpoint exercises again. When every row reads “Getting there” or “Ready”, move on to Part 2, module 10: Iterators and generators. Part 2 builds on these skills: generators stream the files you read here, and decorators wrap the functions you wrote.