05. Functions — Exercises
These exercises practice every idea of the Functions lesson. They use values from the course datasets: sales lines, products, customers, sensor readings and the two JSON files data/config.json and data/customers.json.
How to work:
- Read the task and the expected output or the acceptance criteria.
- Copy the starter code into a script (for example
exercise.py) and replace each to-do comment with your code. - Run the script with
python exercise.py. Compare your output with the expected output. - Stuck? Open one hint at a time. Open the solution only after a real attempt.
Each solution ends with assert checks. Asserts on a function are small tests: they call it with known inputs and check the result. Keep them in your own code. Module 14 turns the same idea into a pytest test suite.
Warm-up
Section titled “Warm-up”M05-W01 · Convert readings with a function
Section titled “M05-W01 · Convert readings with a function”Write a function to_fahrenheit(celsius) that returns the temperature in °F (°F = °C × 9 / 5 + 32). Call it on the three readings and print one line per reading, rounded to 1 decimal.
19.3 °C = 66.7 °F21.06 °C = 69.9 °F22.9 °C = 73.2 °Freadings = [19.3, 21.06, 22.9]
# TODO: define to_fahrenheit(celsius)# TODO: print one line per reading, such as "19.3 °C = 66.7 °F"Hint 1
The body is one line: return celsius * 9 / 5 + 32.
Hint 2
Loop over readings and call the function inside an f-string: f"{c} °C = {to_fahrenheit(c):.1f} °F".
Solution
readings = [19.3, 21.06, 22.9]
def to_fahrenheit(celsius): """Return the temperature in degrees Fahrenheit.""" return celsius * 9 / 5 + 32
for c in readings: print(f"{c} °C = {to_fahrenheit(c):.1f} °F")
assert to_fahrenheit(0) == 32assert to_fahrenheit(100) == 21219.3 °C = 66.7 °F21.06 °C = 69.9 °F22.9 °C = 73.2 °FHow it works:
defcreates the function. Its body runs only when the loop calls it.returnsends the number back. The f-string formats it; the function itself does not round, so callers keep the full value.- The asserts test two points that everyone knows: water freezes at 32 °F and boils at 212 °F.
Alternative: a comprehension builds all results at once when you need a list rather than printed lines: [round(to_fahrenheit(c), 1) for c in readings].
M05-W02 · Predict the output: print or return
Section titled “M05-W02 · Predict the output: print or return”Predict the output: write down what each print() shows, line by line. Then run the code.
Acceptance criteria:
- Write your prediction line by line, then run the code.
- Your prediction matches the Output in the solution.
- You can explain where each
Nonecomes from.
def total_with_tax(amount, rate=0.08): print("computing") return round(amount * (1 + rate), 2)
def log_total(amount): print("total:", amount)
a = total_with_tax(100)b = log_total(a)print(a, b)print(total_with_tax(79.99, rate=0))# TODO: write your prediction for each printed line before you run itHint 1
Every call of total_with_tax prints computing before it returns.
Hint 2
log_total has no return statement. What does such a function return?
Solution
def total_with_tax(amount, rate=0.08): print("computing") return round(amount * (1 + rate), 2)
def log_total(amount): print("total:", amount)
a = total_with_tax(100)b = log_total(a)print(a, b)print(total_with_tax(79.99, rate=0))assert a == 108.0assert b is Nonecomputingtotal: 108.0108.0 Nonecomputing79.99How it works:
total_with_tax(100)printscomputingand returns108.0, which goes intoa.log_total(a)printstotal: 108.0. It has noreturn, sobisNone.print(a, b)shows both values.- The last line calls the function again:
computingappears first, thenprintshows the return value. Withrate=0, the amount does not change.
Alternative: to see the hidden None, run print(log_total(5)) in the REPL. It prints total: 5 and then None.
M05-W03 · Default and keyword arguments
Section titled “M05-W03 · Default and keyword arguments”Write line_revenue(unit_price, quantity=1, discount=0.0) that returns the revenue of a sales line, rounded to 2 decimals. Use it on four real lines of data/sales.csv. Pass only the arguments that differ from the defaults, and pass discount by keyword.
| order_id | product | unit_price | quantity | discount |
|---|---|---|---|---|
| O000004 | Noise-Cancelling Headphones | 249.00 | 1 | 0.1 |
| O000051 | Wireless Earbuds | 79.99 | 1 | 0.05 |
| O000051 | Electric Toothbrush | 59.99 | 4 | 0.0 |
| O000145 | 55-inch 4K Smart TV | 1299.00 | 2 | 0.0 |
O000004 224.1O000051 75.99O000051 239.96O000145 2598.0# TODO: define line_revenue(unit_price, quantity=1, discount=0.0)# TODO: print the four lines with as few arguments as possibleHint 1
The formula is unit_price * quantity * (1 - discount), as in data/sales.csv.
Hint 2
The headphones need only a price and a discount: line_revenue(249.00, discount=0.1). The quantity takes its default of 1.
Solution
def line_revenue(unit_price, quantity=1, discount=0.0): """Return the revenue of one sales line, rounded to cents.""" return round(unit_price * quantity * (1 - discount), 2)
print("O000004", line_revenue(249.00, discount=0.1))print("O000051", line_revenue(79.99, discount=0.05))print("O000051", line_revenue(59.99, 4))print("O000145", line_revenue(1299.00, 2))
assert line_revenue(249.00, discount=0.1) == 224.1assert line_revenue(59.99, 4) == 239.96O000004 224.1O000051 75.99O000051 239.96O000145 2598.0How it works:
quantityanddiscounthave defaults, so a call needs onlyunit_price.discount=0.1skips overquantityby naming the parameter. Positionally you would needline_revenue(249.00, 1, 0.1).- All four results equal the
revenuecolumn of the file.round(..., 2)matches the rule of the dataset.
Alternative: pass everything by keyword, line_revenue(unit_price=59.99, quantity=4). It is longer, but it reads well when a call has many numbers.
M05-W04 · Fix the bug: the total is too small
Section titled “M05-W04 · Fix the bug: the total is too small”Fix the bug: this function should add up the six monthly revenue sums of data/reports/, but it returns the January value.
def total_revenue(revenues): total = 0 for r in revenues: total += r return total
monthly = [14162.33, 4719.04, 12296.72, 10879.04, 6675.86, 8533.40]print(total_revenue(monthly))14162.33Change the function so that it prints the full total, rounded to 2 decimals:
57266.39def total_revenue(revenues): total = 0 for r in revenues: total += r return total # TODO: fix the position of this line
monthly = [14162.33, 4719.04, 12296.72, 10879.04, 6675.86, 8533.40]print(total_revenue(monthly))Hint 1
return ends the function immediately, even in the middle of a loop.
Hint 2
Indentation decides which block a line belongs to. The return must run once, after the loop.
Solution
def total_revenue(revenues): """Return the sum of revenues, rounded to cents.""" total = 0 for r in revenues: total += r return round(total, 2)
monthly = [14162.33, 4719.04, 12296.72, 10879.04, 6675.86, 8533.40]print(total_revenue(monthly))assert total_revenue(monthly) == round(sum(monthly), 2)assert total_revenue([]) == 057266.39How it works:
- In the bug,
returnis inside theforblock. The first pass adds January and returns at once. - Moving
returnfour spaces to the left puts it after the loop, so it runs once, when all six months are added. round(total, 2)hides the float error of the sum.
Alternative: the built-in does the same: round(sum(monthly), 2). Write your own loop only when the step needs more than a sum.
M05-W05 · Predict the output: which variable?
Section titled “M05-W05 · Predict the output: which variable?”Predict the output: use the LEGB rule to decide which unit and which reading each line uses. Then run the code.
Acceptance criteria:
- Write your prediction line by line, then run the code.
- Your prediction matches the Output in the solution.
- For each name in each function, you can say whether it is local or global.
unit = "°C"reading = 21.7
def convert(reading): unit = "°F" return f"{reading * 9 / 5 + 32:.1f} {unit}"
def label(): return f"{reading} {unit}"
print(convert(19.5))print(reading, unit)print(label())# TODO: write your prediction for each printed line before you run itHint 1
A parameter is a local variable. So is any name assigned inside the function.
Hint 2
label() assigns nothing. Where does Python find reading and unit for it?
Solution
unit = "°C"reading = 21.7
def convert(reading): unit = "°F" return f"{reading * 9 / 5 + 32:.1f} {unit}"
def label(): return f"{reading} {unit}"
print(convert(19.5))print(reading, unit)print(label())assert convert(19.5) == "67.1 °F"assert unit == "°C"67.1 °F21.7 °C21.7 °CHow it works:
- In
convert,readingis the parameter (19.5) andunitis assigned inside, so both are local. They hide the globals only inside the function. - The globals never change: the assignment
unit = "°F"created a new local name. labelassigns nothing, so both names fall through Local and Enclosing to the Global scope.
Alternative: print(convert.__code__.co_varnames) lists the local names of a function: ('reading', 'unit'). label has none.
M05-W06 · Any number of quantities
Section titled “M05-W06 · Any number of quantities”Write total_units(*quantities) that returns the sum of any number of quantities. Call it with three numbers, with the list order = [4, 1, 25] unpacked, and with no arguments.
6300order = [4, 1, 25]
# TODO: define total_units(*quantities)# TODO: print total_units(1, 2, 3), the unpacked order and total_units()Hint 1
Inside the function, quantities is a tuple. sum() accepts a tuple.
Hint 2
To pass the items of a list as separate arguments, put * before it in the call: total_units(*order).
Solution
order = [4, 1, 25]
def total_units(*quantities): """Return the total of any number of quantities.""" return sum(quantities)
print(total_units(1, 2, 3))print(total_units(*order))print(total_units())assert total_units(*order) == 30assert total_units() == 06300How it works:
*quantitiescollects all positional arguments into a tuple:(1, 2, 3), then(4, 1, 25), then().*orderin the call unpacks the list into three arguments. Without the star, the function would receive one argument, the list itself, andsum(([4, 1, 25],))would fail.- The sum of an empty tuple is 0, so the call with no arguments works.
Alternative: def total_units(quantities) with one list parameter is often the better design when the data already sits in a list. Use *args when callers naturally write the values one by one.
M05-W07 · Sort stores with a key
Section titled “M05-W07 · Sort stores with a key”Sort these stores from data/stores.csv by floor area, largest first, and print the top three. Then print the store that opened first. ISO dates such as 2008-02-23 sort correctly as text.
S07 New York 3400S04 Houston 3100S01 Chicago 2850oldest: New York 2008-02-23stores = [ {"store_id": "S01", "city": "Chicago", "size_sqm": 2850, "opened": "2009-03-14"}, {"store_id": "S04", "city": "Houston", "size_sqm": 3100, "opened": "2008-11-08"}, {"store_id": "S07", "city": "New York", "size_sqm": 3400, "opened": "2008-02-23"}, {"store_id": "S10", "city": "Seattle", "size_sqm": 2480, "opened": "2010-06-19"}, { "store_id": "S11", "city": "San Francisco", "size_sqm": 1890, "opened": "2014-07-26", }, {"store_id": "S12", "city": "Denver", "size_sqm": 1350, "opened": "2023-06-15"},]# TODO: sort by size_sqm, largest first, and print the top three# TODO: print the store that opened firstHint 1
sorted(stores, key=lambda s: s["size_sqm"], reverse=True) returns a new, sorted list.
Hint 2
min() accepts the same key argument. The earliest date is the smallest string.
Solution
stores = [ {"store_id": "S01", "city": "Chicago", "size_sqm": 2850, "opened": "2009-03-14"}, {"store_id": "S04", "city": "Houston", "size_sqm": 3100, "opened": "2008-11-08"}, {"store_id": "S07", "city": "New York", "size_sqm": 3400, "opened": "2008-02-23"}, {"store_id": "S10", "city": "Seattle", "size_sqm": 2480, "opened": "2010-06-19"}, { "store_id": "S11", "city": "San Francisco", "size_sqm": 1890, "opened": "2014-07-26", }, {"store_id": "S12", "city": "Denver", "size_sqm": 1350, "opened": "2023-06-15"},]
largest = sorted(stores, key=lambda s: s["size_sqm"], reverse=True)for s in largest[:3]: print(s["store_id"], s["city"], s["size_sqm"])oldest = min(stores, key=lambda s: s["opened"])print("oldest:", oldest["city"], oldest["opened"])
assert [s["store_id"] for s in largest[:3]] == ["S07", "S04", "S01"]assert oldest["store_id"] == "S07"S07 New York 3400S04 Houston 3100S01 Chicago 2850oldest: New York 2008-02-23How it works:
- The key function returns the floor area of each store.
sorted()compares those numbers, not the dicts. reverse=Trueputs the largest first.[:3]takes the top three.min()with a key returns the whole dict with the smallestopenedstring. ISO dates put the year first, so text order equals time order.
Alternative: from operator import itemgetter and key=itemgetter("size_sqm") do the same as the lambda. Module 09 shows the operator module.
M05-W08 · Write a Google-style docstring
Section titled “M05-W08 · Write a Google-style docstring”The function below works but has no docstring. Add a Google-style docstring so that inspect.getdoc() prints exactly the expected output.
Return the share of the price that the shop keeps.
Args: price: The selling price. Must be greater than 0. cost: The cost to the shop.
Returns: A fraction such as 0.606 for a 60.6% margin.import inspect
def margin_rate(price, cost): # TODO: add a Google-style docstring return (price - cost) / price
print(inspect.getdoc(margin_rate))Hint 1
The docstring is the first statement of the body, in triple double quotes. It starts with a one-line summary in the imperative mood.
Hint 2
After a blank line, write the section headings Args: and Returns:. Indent each entry under its heading by 4 spaces.
Solution
import inspect
def margin_rate(price, cost): """Return the share of the price that the shop keeps.
Args: price: The selling price. Must be greater than 0. cost: The cost to the shop.
Returns: A fraction such as 0.606 for a 60.6% margin. """ return (price - cost) / price
print(inspect.getdoc(margin_rate))assert margin_rate.__doc__.startswith("Return the share")assert round(margin_rate(79.99, 31.50), 3) == 0.606Return the share of the price that the shop keeps.
Args: price: The selling price. Must be greater than 0. cost: The cost to the shop.
Returns: A fraction such as 0.606 for a 60.6% margin.How it works:
- The string literal on the first line of the body becomes
margin_rate.__doc__. inspect.getdoc()removes the common indentation, so the output starts at the left margin.- The summary says what the function returns.
Args:explains each parameter, including the rule thatpricemust not be 0.Returns:gives the unit of the result with an example.
Alternative: in NumPy style, the same docstring has underlined headings: Parameters above a ---------- line, then price : float on its own line with the text indented below it. It is longer, which pays off only for functions with many parameters.
M05-C01 · A price cleaner with a configurable missing list
Section titled “M05-C01 · A price cleaner with a configurable missing list”Write clean_price(text, *, na_values=("", "N/A", "-")). It returns None for a missing token and the price as a float otherwise. Then write mean_of_valid(values), which returns the mean of the values that are not None. Apply both to the eight raw prices from data/sales_raw.csv below.
[249.0, 29.99, None, 1299.0, None, 14.99, None, 89.5]missing: 3mean of valid prices: 336.50raw = ["$249.00", "$29.99", "N/A", "$1,299.00", "-", "$14.99", "", "$89.50"]
# TODO: define clean_price(text, *, na_values=("", "N/A", "-"))# TODO: define mean_of_valid(values)# TODO: print the cleaned list, the number of missing values and the meanHint 1
Strip the text first. Return None early if the stripped text is in na_values.
Hint 2
Remove both $ and , with replace() before float().
Hint 3
mean_of_valid can build valid = [v for v in values if v is not None] and divide its sum by its length.
Solution
raw = ["$249.00", "$29.99", "N/A", "$1,299.00", "-", "$14.99", "", "$89.50"]
def clean_price(text, *, na_values=("", "N/A", "-")): """Convert a raw price such as "$1,299.00" to a float, or None if missing.""" text = text.strip() if text in na_values: return None return float(text.replace("$", "").replace(",", ""))
def mean_of_valid(values): """Return the mean of the values that are not None.""" valid = [v for v in values if v is not None] return sum(valid) / len(valid)
prices = [clean_price(p) for p in raw]print(prices)print("missing:", prices.count(None))print(f"mean of valid prices: {mean_of_valid(prices):.2f}")
assert clean_price("$1,299.00") == 1299.0assert clean_price(" - ") is Noneassert clean_price("unknown", na_values=("unknown",)) is Noneassert prices.count(None) == 3[249.0, 29.99, None, 1299.0, None, 14.99, None, 89.5]missing: 3mean of valid prices: 336.50How it works:
strip()makes" - "and"-"the same token.- The early
return Nonehandles the missing tokens. The last line handles every real price. na_valuesis keyword-only: a call such asclean_price(x, ("?",))would hide what the tuple means. The default is a tuple, so it cannot be changed by accident.mean_of_validignoresNoneinstead of treating it as 0, which would pull the mean down.
Alternative: pass the list from the config file: clean_price(p, na_values=config["cleaning"]["na_values"]). A list works with in as well as a tuple does.
M05-C02 · Year-over-year growth of web traffic
Section titled “M05-C02 · Year-over-year growth of web traffic”The mean daily visits in data/web_traffic.csv were 3,511.7 in 2022, 4,057.7 in 2023 and 5,496.9 in 2024. Write percent_change(*, old, new) and growth_lines(values, labels, *, digits=1). The second function returns one text line per year after the first, as shown.
2023: +15.5% vs previous year2024: +35.5% vs previous year['2023: +15.55% vs previous year', '2024: +35.47% vs previous year']years = ["2022", "2023", "2024"]visits = [3511.7, 4057.7, 5496.9]
# TODO: define percent_change(*, old, new)# TODO: define growth_lines(values, labels, *, digits=1) that returns a list of str# TODO: print each line, then the lines with digits=2Hint 1
zip(values, values[1:]) gives the pairs (2022, 2023) and (2023, 2024).
Hint 2
A format spec can take its precision from a variable: f"{change:+.{digits}f}%".
Solution
years = ["2022", "2023", "2024"]visits = [3511.7, 4057.7, 5496.9]
def percent_change(*, old, new): """Return the change from old to new, in percent.""" return (new - old) / old * 100
def growth_lines(values, labels, *, digits=1): """Return one "label: +x.x%" line per value after the first.""" lines = [] for label, (old, new) in zip(labels[1:], zip(values, values[1:])): change = percent_change(old=old, new=new) lines.append(f"{label}: {change:+.{digits}f}% vs previous year") return lines
for line in growth_lines(visits, years): print(line)print(growth_lines(visits, years, digits=2))
assert round(percent_change(old=3511.7, new=4057.7), 1) == 15.5assert len(growth_lines(visits, years)) == 22023: +15.5% vs previous year2024: +35.5% vs previous year['2023: +15.55% vs previous year', '2024: +35.47% vs previous year']How it works:
percent_changeforces names, sooldandnewcannot be swapped by accident.- The inner
zipbuilds the (old, new) pairs. The outerzipadds the label of the newer year. {change:+.{digits}f}puts the value ofdigitsinto the format spec.+shows the sign.- The function returns lines instead of printing them, so the caller decides: print them, write them to a file or check them in a test.
Alternative: a comprehension builds the same list: [f"{lab}: {percent_change(old=a, new=b):+.1f}%" for lab, a, b in zip(labels[1:], values, values[1:])]. zip accepts three iterables and stops at the shortest.
M05-C03 · Choose and justify: design the signature of a scaler
Section titled “M05-C03 · Choose and justify: design the signature of a scaler”Choose a method and justify it: a teammate wrote scale(values, low, high) for min-max scaling, which maps the smallest value to low and the largest to high. Calls look like scale(shift, 0, 1). Redesign the signature with / and * and the defaults low=0.0 and high=1.0. Write one sentence of justification for each marker. Then implement it with the formula below and scale the sensor shift (lines 37–42 of data/readings.txt).
(values, /, *, low=0.0, high=1.0)[0.0, 0.71, 0.35, 1.0, 1.0, 0.76][-1.0, 0.41, -0.29, 1.0, 1.0, 0.53]import inspect
shift = [19.5, 20.7, 20.1, 21.2, 21.2, 20.8]
# TODO: def min_max_scale(...) with / and * in the right places# Justify each marker in a comment.# TODO: print the signature, the scaled shift (2 decimals) and the shift scaled to -1..1Hint 1
Which parameter is the data, and which ones are options? A caller should never need to write values=.
Hint 2
The data goes before /; every option goes after *. Which group is values in, and which group are low and high in?
Solution
import inspect
shift = [19.5, 20.7, 20.1, 21.2, 21.2, 20.8]
def min_max_scale(values, /, *, low=0.0, high=1.0): """Map values linearly so that min -> low and max -> high.
Args: values: The numbers to scale. At least two different values. low: The target of the smallest value. high: The target of the largest value.
Returns: A new list of scaled values. """ # /: "values" means nothing to callers, so we stay free to rename it. # *: low and high are options; scale(x, 0, 1) hides their meaning. smallest, largest = min(values), max(values) span = largest - smallest return [low + (v - smallest) / span * (high - low) for v in values]
print(inspect.signature(min_max_scale))print([round(v, 2) for v in min_max_scale(shift)])print([round(v, 2) for v in min_max_scale(shift, low=-1.0, high=1.0)])
scaled = min_max_scale(shift)assert min(scaled) == 0.0 and max(scaled) == 1.0assert inspect.signature(min_max_scale).parameters["low"].kind.name == "KEYWORD_ONLY"(values, /, *, low=0.0, high=1.0)[0.0, 0.71, 0.35, 1.0, 1.0, 0.76][-1.0, 0.41, -0.29, 1.0, 1.0, 0.53]How it works:
/aftervalues: the data is always the first argument, and its name is an internal detail. Positional-only lets you rename it later without breaking any call.*before the options:lowandhighare settings. Forcing their names makes every call self-explaining (low=-1.0), and you can add options later in any order.- The comprehension applies the formula to every value. 19.5 becomes 0.0 and 21.2 becomes 1.0.
- The function returns a new list and does not change
shift. It is a pure function.
Alternative: scikit-learn makes a similar choice: in MinMaxScaler(feature_range=(0, 1), *, copy=True, clip=False), everything after feature_range is keyword-only. Module 33 uses it.
M05-C04 · Forward summary options with **kwargs
Section titled “M05-C04 · Forward summary options with **kwargs”summarize is given. Write compare_shifts(shifts, **summary_options). It takes a dict of shift name → readings, calls summarize on each with the forwarded options, and returns a list of lines. Use the two shifts from data/readings.txt (lines 1–6 and lines 37–42). Print the lines with the default precision, then with digits=2.
A (lines 1-6) n=6 mean=21.7 max=22.1B (lines 37-42) n=6 mean=20.6 max=21.2A (lines 1-6) n=6 mean=21.68 max=22.1B (lines 37-42) n=6 mean=20.58 max=21.2def summarize(readings, *, digits=1): """Return the count, min, max and mean of readings, rounded.""" return { "count": len(readings), "min": round(min(readings), digits), "max": round(max(readings), digits), "mean": round(sum(readings) / len(readings), digits), }
shifts = { "A (lines 1-6)": [21.0, 21.9, 21.4, 21.7, 22.1, 22.0], "B (lines 37-42)": [19.5, 20.7, 20.1, 21.2, 21.2, 20.8],}
# TODO: define compare_shifts(shifts, **summary_options)# TODO: print the lines with the default precision, then with digits=2Hint 1
Inside compare_shifts, call summarize(readings, **summary_options). The two stars unpack the dict again.
Hint 2
Loop with for name, readings in shifts.items(): and build one f-string per shift.
Solution
def summarize(readings, *, digits=1): """Return the count, min, max and mean of readings, rounded.""" return { "count": len(readings), "min": round(min(readings), digits), "max": round(max(readings), digits), "mean": round(sum(readings) / len(readings), digits), }
shifts = { "A (lines 1-6)": [21.0, 21.9, 21.4, 21.7, 22.1, 22.0], "B (lines 37-42)": [19.5, 20.7, 20.1, 21.2, 21.2, 20.8],}
def compare_shifts(shifts, **summary_options): """Return one summary line per shift; options are forwarded to summarize().""" lines = [] for name, readings in shifts.items(): s = summarize(readings, **summary_options) lines.append(f"{name:<16} n={s['count']} mean={s['mean']} max={s['max']}") return lines
for line in compare_shifts(shifts): print(line)for line in compare_shifts(shifts, digits=2): print(line)
assert compare_shifts(shifts)[0].endswith("mean=21.7 max=22.1")assert len(compare_shifts(shifts, digits=3)) == 2A (lines 1-6) n=6 mean=21.7 max=22.1B (lines 37-42) n=6 mean=20.6 max=21.2A (lines 1-6) n=6 mean=21.68 max=22.1B (lines 37-42) n=6 mean=20.58 max=21.2How it works:
**summary_optionscollectsdigits=2into the dict{"digits": 2}. With no options, the dict is empty.summarize(readings, **summary_options)unpacks the dict back into keyword arguments. An empty dict adds nothing, sosummarizeuses its default.compare_shiftsnever mentionsdigits. Ifsummarizegains a new option,compare_shiftsforwards it with no change.
Alternative: name the option explicitly: def compare_shifts(shifts, *, digits=1) and call summarize(readings, digits=digits). This is clearer when there is one option and it never changes. Forwarding pays off when the inner function has many options.
M05-C05 · Churn rules built by closures
Section titled “M05-C05 · Churn rules built by closures”In data/customers.csv, churn is high for short tenure (tenure_months ≤ 6), few logins (logins_last_30d ≤ 3) and many tickets (support_tickets ≥ 4). Write two factories, make_at_most(column, limit) and make_at_least(column, limit), that return rule functions. Each rule takes a customer dict and returns a bool. Count how many rules each of these six real customers breaks.
C00101: 0 of 3 rulesC00103: 0 of 3 rulesC04801: 2 of 3 rulesC04805: 1 of 3 rulesC04807: 1 of 3 rulesC04810: 2 of 3 rulescustomers = [ {"customer_id": "C00101", "tenure_months": 72, "logins_last_30d": 6, "support_tickets": 0}, {"customer_id": "C00103", "tenure_months": 72, "logins_last_30d": 4, "support_tickets": 1}, {"customer_id": "C04801", "tenure_months": 1, "logins_last_30d": 2, "support_tickets": 2}, {"customer_id": "C04805", "tenure_months": 1, "logins_last_30d": 4, "support_tickets": 1}, {"customer_id": "C04807", "tenure_months": 1, "logins_last_30d": 10, "support_tickets": 3}, {"customer_id": "C04810", "tenure_months": 1, "logins_last_30d": 5, "support_tickets": 4},]
# TODO: define make_at_most(column, limit) and make_at_least(column, limit)# TODO: build the three rules, then print "<id>: <n> of 3 rules" per customerHint 1
The inner function is def rule(customer): return customer[column] <= limit. Return rule, without parentheses.
Hint 2
True counts as 1 in a sum, so sum(rule(c) for rule in rules) counts the broken rules.
Solution
customers = [ {"customer_id": "C00101", "tenure_months": 72, "logins_last_30d": 6, "support_tickets": 0}, {"customer_id": "C00103", "tenure_months": 72, "logins_last_30d": 4, "support_tickets": 1}, {"customer_id": "C04801", "tenure_months": 1, "logins_last_30d": 2, "support_tickets": 2}, {"customer_id": "C04805", "tenure_months": 1, "logins_last_30d": 4, "support_tickets": 1}, {"customer_id": "C04807", "tenure_months": 1, "logins_last_30d": 10, "support_tickets": 3}, {"customer_id": "C04810", "tenure_months": 1, "logins_last_30d": 5, "support_tickets": 4},]
def make_at_most(column, limit): """Return a rule that is True when customer[column] <= limit."""
def rule(customer): return customer[column] <= limit
return rule
def make_at_least(column, limit): """Return a rule that is True when customer[column] >= limit."""
def rule(customer): return customer[column] >= limit
return rule
rules = [ make_at_most("tenure_months", 6), make_at_most("logins_last_30d", 3), make_at_least("support_tickets", 4),]for c in customers: broken = sum(rule(c) for rule in rules) print(f"{c['customer_id']}: {broken} of 3 rules")
assert rules[0](customers[2]) is Trueassert sum(rule(customers[0]) for rule in rules) == 0C00101: 0 of 3 rulesC00103: 0 of 3 rulesC04801: 2 of 3 rulesC04805: 1 of 3 rulesC04807: 1 of 3 rulesC04810: 2 of 3 rulesHow it works:
- Each factory call creates a new
rulethat remembers its owncolumnandlimit. - The three rules have the same shape, so a list holds them and one loop applies them all.
- Each rule returns a
bool.sum()counts theTruevalues. - C04801 is new and barely logs in: two rules. C04810 is new and has 4 tickets: two rules. The long-tenure customers break none.
Alternative: one factory with an operator argument: make_rule(column, limit, *, at_most=True). It saves a function but adds a flag, and flags make calls harder to read. Two small, clearly named factories are easier to read.
M05-C06 · Fix the bug: a status counter that crashes
Section titled “M05-C06 · Fix the bug: a status counter that crashes”Fix the bug: make_status_counter() should return a function that counts how often it has seen a "warn" or "fail" status. It crashes on the first alert. The statuses are 12 real readings of sensor S4 from data/sensors.csv, starting at 2024-05-03 09:20.
def make_status_counter(): alerts = 0
def count(status): if status != "ok": alerts += 1 return alerts
return count
statuses = ["ok"] * 8 + ["fail", "ok", "ok", "warn"]counter = make_status_counter()for s in statuses: total = counter(s)print(total)UnboundLocalError: cannot access local variable 'alerts' where it is not associated with a valueFix the inner function so that the script prints the number of alerts:
2def make_status_counter(): alerts = 0
def count(status): # TODO: tell Python that alerts belongs to the enclosing function if status != "ok": alerts += 1 return alerts
return count
statuses = ["ok"] * 8 + ["fail", "ok", "ok", "warn"]counter = make_status_counter()for s in statuses: total = counter(s)print(total)Hint 1
alerts += 1 is an assignment. An assignment makes alerts local to count.
Hint 2
One statement at the top of count makes alerts refer to the variable of make_status_counter.
Solution
def make_status_counter(): """Return a function that counts the non-"ok" statuses it has seen.""" alerts = 0
def count(status): nonlocal alerts if status != "ok": alerts += 1 return alerts
return count
statuses = ["ok"] * 8 + ["fail", "ok", "ok", "warn"]counter = make_status_counter()for s in statuses: total = counter(s)print(total)
other = make_status_counter()assert other("warn") == 1assert counter("ok") == 22How it works:
- The first eight statuses are
"ok", so the bug stays hidden until the"fail". Only then doesalerts += 1run and read the localalerts, which has no value yet. nonlocal alertstells Python thatalertsis the variable of the enclosing function. Now+=updates it.- Each counter has its own
alerts:otherstarts from 0 and does not changecounter.
Alternative: keep the state in a mutable object, such as counts = {"alerts": 0} and counts["alerts"] += 1. This works without nonlocal, because it changes the dict and never assigns to the name counts. nonlocal is clearer for a single number.
M05-C07 · Refactor: lambdas to a comprehension
Section titled “M05-C07 · Refactor: lambdas to a comprehension”Refactor: this line selects the products that cost 100 USD or more and gives them a 20% promo price. It works, but it is hard to read. Rewrite it with a named function promo_price(price, *, rate) and a list comprehension. The output must not change.
list_prices = [79.99, 249.00, 1299.00, 59.99, 349.00, 129.95, 14.99]promo = list(map(lambda p: round(p * (1 - 0.2), 2), filter(lambda p: p >= 100, list_prices)))print(promo)[199.2, 1039.2, 279.2, 103.96][199.2, 1039.2, 279.2, 103.96]list_prices = [79.99, 249.00, 1299.00, 59.99, 349.00, 129.95, 14.99]
# TODO: define promo_price(price, *, rate)# TODO: rewrite the map/filter line as a comprehension that calls promo_priceHint 1
A comprehension with a filter has the shape [expression for item in items if condition].
Hint 2
Move the filter lambda into the if part of the comprehension and the map lambda into the named function.
Solution
list_prices = [79.99, 249.00, 1299.00, 59.99, 349.00, 129.95, 14.99]
def promo_price(price, *, rate): """Return the price after a discount of rate (0.2 means 20%), in cents.""" return round(price * (1 - rate), 2)
promo = [promo_price(p, rate=0.2) for p in list_prices if p >= 100]print(promo)assert promo == [199.2, 1039.2, 279.2, 103.96]assert promo_price(100, rate=0) == 100[199.2, 1039.2, 279.2, 103.96]How it works:
- The original line also breaks the 88-character limit of PEP 8, which is a hint that it does too much.
- The comprehension reads in order: take
pfromlist_prices, keep it if it is at least 100, compute its promo price. promo_pricehas a name, a docstring and a required keyword-onlyrate. The callpromo_price(p, rate=0.2)says what0.2is, and you can test the function on its own.
Alternative: map with a named function stays readable when no lambda is needed: list(map(clean_price, raw)). The trouble in the original was the two lambdas, not map itself.
M05-C08 · Best margin per category
Section titled “M05-C08 · Best margin per category”For each category, find the product with the highest margin rate (price − cost) / price. Print the categories A to Z. The products are real rows of data/products.csv.
Beauty Mineral Sunscreen SPF 50 74.4%Books Harbor Lane Mysteries 68.2%Clothing Organic Cotton T-Shirt 69.5%Electronics Wireless Earbuds 60.6%Home Chef's Knife Set 63.1%Sports Non-Slip Yoga Mat 68.6%products = [ ("P001", "Wireless Earbuds", "Electronics", 31.50, 79.99), ("P004", "14-inch Ultrabook Laptop", "Electronics", 780.00, 1149.00), ("P006", "Espresso Machine", "Home", 162.00, 349.00), ("P008", "Chef's Knife Set", "Home", 48.00, 129.95), ("P013", "Slim Fit Jeans", "Clothing", 19.50, 59.99), ("P015", "Organic Cotton T-Shirt", "Clothing", 6.10, 19.99), ("P017", "Non-Slip Yoga Mat", "Sports", 11.00, 34.99), ("P018", "Adjustable Dumbbells", "Sports", 128.00, 279.00), ("P021", "Harbor Lane Mysteries", "Books", 5.40, 16.99), ("P024", "Statistics Made Simple", "Books", 11.20, 34.99), ("P027", "Hydrating Face Cream", "Beauty", 9.10, 32.00), ("P030", "Mineral Sunscreen SPF 50", "Beauty", 4.10, 15.99),]# Each tuple: (product_id, product, category, unit_cost, unit_price)
# TODO: define margin_rate(product)# TODO: for each category, A to Z, print the product with the best margin rateHint 1
sorted({p[2] for p in products}) gives the categories A to Z.
Hint 2
For one category, max([p for p in products if p[2] == cat], key=margin_rate) returns the best product.
Solution
products = [ ("P001", "Wireless Earbuds", "Electronics", 31.50, 79.99), ("P004", "14-inch Ultrabook Laptop", "Electronics", 780.00, 1149.00), ("P006", "Espresso Machine", "Home", 162.00, 349.00), ("P008", "Chef's Knife Set", "Home", 48.00, 129.95), ("P013", "Slim Fit Jeans", "Clothing", 19.50, 59.99), ("P015", "Organic Cotton T-Shirt", "Clothing", 6.10, 19.99), ("P017", "Non-Slip Yoga Mat", "Sports", 11.00, 34.99), ("P018", "Adjustable Dumbbells", "Sports", 128.00, 279.00), ("P021", "Harbor Lane Mysteries", "Books", 5.40, 16.99), ("P024", "Statistics Made Simple", "Books", 11.20, 34.99), ("P027", "Hydrating Face Cream", "Beauty", 9.10, 32.00), ("P030", "Mineral Sunscreen SPF 50", "Beauty", 4.10, 15.99),]
def margin_rate(product): """Return (price - cost) / price for a (id, name, category, cost, price) row.""" _, _, _, cost, price = product return (price - cost) / price
best = {}for category in sorted({p[2] for p in products}): in_category = [p for p in products if p[2] == category] best[category] = max(in_category, key=margin_rate) p = best[category] print(f"{category:<12} {p[1]:<24} {margin_rate(p):.1%}")
assert best["Electronics"][0] == "P001"assert len(best) == 6Beauty Mineral Sunscreen SPF 50 74.4%Books Harbor Lane Mysteries 68.2%Clothing Organic Cotton T-Shirt 69.5%Electronics Wireless Earbuds 60.6%Home Chef's Knife Set 63.1%Sports Non-Slip Yoga Mat 68.6%How it works:
margin_rateunpacks the tuple. The_names mark the fields it does not need.- The set comprehension finds the distinct categories, and
sorted()orders them A to Z. - For each category,
max(..., key=margin_rate)returns the whole row with the largest margin rate, so you keep the product name.
Alternative: sort once by (category, -margin_rate(p)) and keep the first row of each category: for p in sorted(products, key=lambda p: (p[2], -margin_rate(p))) with a “seen” set. It visits the list once instead of once per category, which matters for large data. pandas does this with groupby (module 25).
M05-C09 · Count the value types in a JSON file
Section titled “M05-C09 · Count the value types in a JSON file”Write a recursive function count_types(obj) that walks dicts and lists and returns a dict that maps each leaf type name ("str", "int", "float", "bool") to the number of leaves of that type. Run it on data/config.json and print the counts sorted by type name. Lists count as containers, not as leaves.
bool 3float 5int 8str 29total leaves: 45import json
with open("data/config.json", encoding="utf-8") as f: config = json.load(f)
# TODO: define count_types(obj) with a base case for leaves# TODO: print the counts, sorted by type nameHint 1
Base case: a leaf returns {type(obj).__name__: 1}.
Hint 2
Recursive case: make an empty dict, call count_types on each child and add the child’s counts into it with counts[name] = counts.get(name, 0) + n.
Solution
import json
with open("data/config.json", encoding="utf-8") as f: config = json.load(f)
def count_types(obj): """Return {type name: number of leaves} for nested dicts and lists.""" if isinstance(obj, dict): children = obj.values() elif isinstance(obj, list): children = obj else: # base case: one leaf return {type(obj).__name__: 1} counts = {} for child in children: for name, n in count_types(child).items(): counts[name] = counts.get(name, 0) + n return counts
counts = count_types(config)for name in sorted(counts): print(f"{name:<6} {counts[name]}")print("total leaves:", sum(counts.values()))
assert count_types(3) == {"int": 1}assert count_types({"a": [1, 2.0], "b": {"c": "x"}}) == {"int": 1, "float": 1, "str": 1}bool 3float 5int 8str 29total leaves: 45How it works:
- The two container branches only choose the children. The shared loop then recurses into each child.
- The base case returns a one-entry dict for any leaf.
- Each level merges the counts of its children. The top call returns the counts for the whole file.
- JSON
trueandfalseload asbool, and JSON numbers load asintorfloat, depending on whether they have a decimal point.
Alternative: collections.Counter (module 09) adds counts with +: return sum((count_types(c) for c in children), Counter()). The idea is the same.
M05-C10 · Read a setting by its dotted path
Section titled “M05-C10 · Read a setting by its dotted path”Write a recursive function get_path(obj, path, *, default=None) that reads a value from nested dicts with a dotted path such as "model.params.C". It returns default when any key on the way is missing. Test it on data/config.json.
1.050lbfgsINFONoneimport json
with open("data/config.json", encoding="utf-8") as f: config = json.load(f)
# TODO: define get_path(obj, path, *, default=None)# TODO: print model.params.C, thresholds.max_quantity, model.params.solver# (with the default "lbfgs") and logging.levelHint 1
path.partition(".") splits "model.params.C" into ("model", ".", "params.C").
Hint 2
Base case: no dot left, so return obj.get(path, default). Recursive case: look up the first key and call get_path on the value with the rest of the path.
Hint 3
If the value on the way is not a dict, or the key is missing, return default at once.
Solution
import json
with open("data/config.json", encoding="utf-8") as f: config = json.load(f)
def get_path(obj, path, *, default=None): """Return the value at a dotted path such as "model.params.C", or default.""" if not isinstance(obj, dict): return default head, _, rest = path.partition(".") if not rest: # base case: the last key return obj.get(head, default) if head not in obj: return default return get_path(obj[head], rest, default=default)
print(get_path(config, "model.params.C"))print(get_path(config, "thresholds.max_quantity"))print(get_path(config, "model.params.solver", default="lbfgs"))print(get_path(config, "logging.level"))print(get_path(config, "project.name"))
assert get_path(config, "retry.attempts") == 3assert get_path(config, "nope.x", default=0) == 01.050lbfgsINFONoneHow it works:
- Each call removes one key from the front of the path and goes one level down.
- The base case is the last key:
dict.get()returns the value or the default. "project.name"returnsNone, becauseconfig["project"]is the string"sales-pipeline", not a dict. The firstifcatches this.defaultis keyword-only, so every call shows that0is the fallback, not part of the lookup:get_path(config, "a.b", default=0). The recursive call must forward it, or a deep miss would returnNoneinstead.
Alternative: a loop works as well, because the path is a flat list of keys: for key in path.split("."): and step one level per key. Recursion and iteration are equally clear here; recursion becomes the better tool when the shape itself is unknown, as in count_types.
M05-C11 · Interpret: why is the mean discount so high?
Section titled “M05-C11 · Interpret: why is the mean discount so high?”Interpret a result: an analyst cleaned seven discount values of data/sales_raw.csv and computed the mean discount with this code. The overall mix in the dataset is 67.5% of lines at 0 discount, so a mean of 0.117 looks wrong. Explain the cause, then fix the function so it ignores only missing values.
discounts = [0.0, 0.05, None, 0.1, 0.0, 0.2, None]
def mean_discount(values): valid = list(filter(None, values)) return sum(valid) / len(valid)
print(f"mean discount: {mean_discount(discounts):.3f}")mean discount: 0.117mean discount: 0.070values used: 5discounts = [0.0, 0.05, None, 0.1, 0.0, 0.2, None]
def mean_discount(values): valid = list(filter(None, values)) # TODO: keep 0.0, drop only None return sum(valid) / len(valid)
print(f"mean discount: {mean_discount(discounts):.3f}")# TODO: print how many values the mean usesHint 1
Print list(filter(None, discounts)). Which values are gone?
Hint 2
filter(None, ...) keeps truthy values. 0.0 is falsy.
Solution
discounts = [0.0, 0.05, None, 0.1, 0.0, 0.2, None]
def mean_discount(values): """Return the mean of the values that are not None.""" valid = [v for v in values if v is not None] return sum(valid) / len(valid)
print(f"mean discount: {mean_discount(discounts):.3f}")print("values used:", len([v for v in discounts if v is not None]))assert round(mean_discount(discounts), 2) == 0.07assert mean_discount([0.0, None]) == 0.0mean discount: 0.070values used: 5How it works:
- Interpretation:
filter(None, values)keeps only truthy values. It dropped the twoNonevalues, as intended, and also the two real0.0discounts. The mean then used 3 values instead of 5 and ignored every full-price line, so it overstated the discount. - The comprehension tests for the exact condition,
is not None, and keeps the zeros. - The second assert pins the bug down: with the old code,
[0.0, None]would leave no values and raiseZeroDivisionError.
Alternative: filter(lambda v: v is not None, values) also works. The comprehension is shorter and needs no lambda.
M05-C12 · Fix the bug: missing fields leak between customers
Section titled “M05-C12 · Fix the bug: missing fields leak between customers”Fix the bug: missing_fields(record, required) should list the required fields that one customer record lacks, either because the key is absent or because its value is None. The records are flattened versions of C00005 and C00010 from data/customers.json: postal_code comes from the nested address. C00005 has no postal_code and no phone key; C00010 has a postal code and "phone": null. The second call reports a field that C00010 does not miss.
def missing_fields(record, required, found=[]): for field in required: if record.get(field) is None: found.append(field) return found
required = ("plan", "postal_code", "phone")c00005 = {"customer_id": "C00005", "plan": "basic", "city": "Chicago"}c00010 = {"customer_id": "C00010", "plan": "premium", "postal_code": "20827", "phone": None}print(missing_fields(c00005, required))print(missing_fields(c00010, required))['postal_code', 'phone']['postal_code', 'phone', 'phone']Fix the function so that each call reports only its own record:
['postal_code', 'phone']['phone']def missing_fields(record, required, found=[]): # TODO: fix the default for field in required: if record.get(field) is None: found.append(field) return found
required = ("plan", "postal_code", "phone")c00005 = {"customer_id": "C00005", "plan": "basic", "city": "Chicago"}c00010 = {"customer_id": "C00010", "plan": "premium", "postal_code": "20827", "phone": None}print(missing_fields(c00005, required))print(missing_fields(c00010, required))Hint 1
When does Python create the list [] in the def line: at every call, or once?
Hint 2
Use None as the default, and create a new list inside the body when the caller passes nothing.
Solution
def missing_fields(record, required, found=None): """Return the required fields that record lacks or holds as None.
Args: record: One flat customer dict. required: The field names that must have a value. found: A list to extend. A new list is created when omitted.
Returns: The list of missing field names, in the order of required. """ if found is None: found = [] for field in required: if record.get(field) is None: found.append(field) return found
required = ("plan", "postal_code", "phone")c00005 = {"customer_id": "C00005", "plan": "basic", "city": "Chicago"}c00010 = {"customer_id": "C00010", "plan": "premium", "postal_code": "20827", "phone": None}print(missing_fields(c00005, required))print(missing_fields(c00010, required))assert missing_fields(c00010, required) == ["phone"]assert missing_fields({"plan": "basic"}, ("plan",)) == []['postal_code', 'phone']['phone']How it works:
- In the bug, Python creates the default list once, when it runs the
defline. Both calls append to that one list, so C00005’s fields show up again for C00010. record.get(field)returnsNoneboth for an absent key and for a storedNone, so one test covers both kinds of gap in the real file.Noneis immutable, so it is a safe default. The body creates a fresh list on every call that does not pass one.- Ruff flags the original with rule B006 (“mutable argument default”). Let your linter catch this bug for you.
Alternative: drop the accumulator and return a comprehension: return [f for f in required if record.get(f) is None]. Without the extra parameter, the bug cannot happen. Keep found only if callers really need to collect fields across records.
Challenge
Section titled “Challenge”M05-X01 · A cleaning pipeline built from a config
Section titled “M05-X01 · A cleaning pipeline built from a config”A pipeline config lists cleaning steps by name, for example ["strip", "collapse", "lower"]. Build the pipeline from a registry, a dict that maps each step name to a function. Your code must:
- Reject a config with an unknown step name and give a clear message.
- Build the pipeline with a factory,
build_pipeline(names, *, registry), that returns two things: the pipeline function and a dict that counts how many values each step changed. - Clean these real product names from
data/sales_raw.csvinto match keys, then print the counts and the number of distinct products. - Run a second config,
["collapse", "title"], and use the counts to find the step that changes data it should not change.
config rejected: unknown step 'titel'; choose from strip, collapse, lower, titlestrip changed 6 of 8collapse changed 2 of 8lower changed 8 of 8distinct products: 7title changed 1 name(s): ["Chef'S Knife Set"]raw_names = [ "Non-Slip Yoga Mat ", " Adjustable Dumbbells", " Air Purifier", "Espresso Machine", "Chef's Knife Set ", "Waterproof Rain Jacket", "Fitness Tracker ", " Fitness Tracker",]
def collapse_spaces(text): """Replace every run of whitespace with one space.""" return " ".join(text.split())
STEPS = { "strip": str.strip, "collapse": collapse_spaces, "lower": str.lower, "title": str.title,}
# TODO: define unknown_steps(names, registry) -> list of unknown names# TODO: define build_pipeline(names, *, registry) -> (pipeline, changes)# TODO: check the config ["collapse", "titel"] and print a clear message# TODO: run ["strip", "collapse", "lower"], print the changes and the distinct count# TODO: run ["collapse", "title"] and print the names that "title" changedHint 1
unknown_steps is one comprehension: keep each name that is not a key of the registry.
Hint 2
In the factory, create changes = dict.fromkeys(names, 0) next to the list of steps. The inner pipeline closure can update the dict without nonlocal, because it changes the dict and never reassigns the name.
Hint 3
Inside the loop of pipeline, compute new = step(value), add 1 to changes[name] when new != value, then continue with value = new.
Solution
raw_names = [ "Non-Slip Yoga Mat ", " Adjustable Dumbbells", " Air Purifier", "Espresso Machine", "Chef's Knife Set ", "Waterproof Rain Jacket", "Fitness Tracker ", " Fitness Tracker",]
def collapse_spaces(text): """Replace every run of whitespace with one space.""" return " ".join(text.split())
STEPS = { "strip": str.strip, "collapse": collapse_spaces, "lower": str.lower, "title": str.title,}
def unknown_steps(names, registry): """Return the step names that are not in registry.""" return [name for name in names if name not in registry]
def build_pipeline(names, *, registry): """Build a cleaning pipeline from step names.
Args: names: Step names, applied from left to right. registry: A dict of step name -> function of one str.
Returns: A tuple (pipeline, changes). pipeline(value) applies the steps; changes maps each step name to how many values it has changed. """ steps = [(name, registry[name]) for name in names] changes = dict.fromkeys(names, 0)
def pipeline(value): for name, step in steps: new = step(value) if new != value: changes[name] += 1 value = new return value
return pipeline, changes
bad = unknown_steps(["collapse", "titel"], STEPS)print(f"config rejected: unknown step {bad[0]!r}; choose from {', '.join(STEPS)}")
make_key, changes = build_pipeline(["strip", "collapse", "lower"], registry=STEPS)keys = [make_key(n) for n in raw_names]for name, count in changes.items(): print(f"{name:<9} changed {count} of {len(raw_names)}")print("distinct products:", len(set(keys)))
tidy, title_changes = build_pipeline(["collapse", "title"], registry=STEPS)tidied = [tidy(n) for n in raw_names]changed = [new for new, n in zip(tidied, raw_names) if new != collapse_spaces(n)]print("title changed", title_changes["title"], "name(s):", changed)
assert unknown_steps(["strip", "lower"], STEPS) == []assert build_pipeline([], registry=STEPS)[0](" x ") == " x "assert changes == {"strip": 6, "collapse": 2, "lower": 8}assert title_changes == {"collapse": 8, "title": 1}assert len(set(keys)) == 7config rejected: unknown step 'titel'; choose from strip, collapse, lower, titlestrip changed 6 of 8collapse changed 2 of 8lower changed 8 of 8distinct products: 7title changed 1 name(s): ["Chef'S Knife Set"]How it works:
- Validation first.
unknown_stepsfinds"titel"before any data is touched. Reporting the valid names in the message tells the user how to fix the config. (Module 06 shows how to stop the program withraiseinstead.) - Registry. The config holds only strings. The dict turns each name into a function, so a config file can choose the steps without containing code.
- Factory and closure.
build_pipelinereturns the pipeline and its counter dict. The closure keeps bothstepsandchanges, and each pipeline has its own counts. - Change counts.
stripchanged the 6 names with spaces at the ends,collapsethe 2 with double inner spaces, andlowerall 8.collapsealone would also remove the end spaces; withstripfirst, the counts show which step did which job. The twoFitness Trackerspellings become one key, so 7 products remain. - The suspicious step. The names in the file are already in title case, so
titleshould change nothing. It changed one name,Chef's Knife Set, intoChef'S Knife Set, becausestr.title()capitalizes the letter after an apostrophe. Counting changes per step is a cheap way to catch a step that damages data.
Alternative: the pipeline could take the functions directly, build_pipeline([str.strip, collapse_spaces]). That is simpler in code, but a config file cannot hold functions. The registry is the usual bridge between a text config and code, for example to choose a model class by name.
M05-X02 · Rank customers within each plan
Section titled “M05-X02 · Rank customers within each plan”Marketing wants the top 2 customers of each plan in data/customers.json, with their signup date and the date of their last order, plus the customers with no orders. find_values from the lesson is given. Write:
total_spend(customer): the sum of the order amounts, withfind_values.last_order(customer): the latest order date, or"none". ISO dates compare correctly as text.group_by(records, key): a higher-order function that returns a dict ofkey(record)→ list of records.top_n(records, n=2, *, key): thenrecords with the largestkey(record).
Print the plans in the fixed order basic, standard, premium.
basic (7 customers) C00017 Mateo Lopez 2,324.98 USD signup 2018-12-02 last order 2024-10-11 C00015 Omar Farouk 1,365.28 USD signup 2018-12-02 last order 2024-04-07standard (7 customers) C00019 Ravi Patel 1,763.46 USD signup 2018-12-02 last order 2023-06-03 C00002 James Okafor 961.89 USD signup 2018-12-01 last order 2024-11-27premium (6 customers) C00003 Mei Chen 2,070.07 USD signup 2018-12-01 last order 2024-12-05 C00001 Ana Silva 1,325.54 USD signup 2018-12-01 last order 2023-12-21no orders: C00008, C00012, C00013import json
with open("data/customers.json", encoding="utf-8") as f: data = json.load(f)customers = data["customers"]
def find_values(obj, key): """Return every value stored under key, at any depth of dicts and lists.""" found = [] if isinstance(obj, dict): for k, value in obj.items(): if k == key: found.append(value) found.extend(find_values(value, key)) elif isinstance(obj, list): for item in obj: found.extend(find_values(item, key)) return found
# TODO: total_spend(customer), last_order(customer)# TODO: group_by(records, key), top_n(records, n=2, *, key)# TODO: for each plan: a header line, then the top 2 customers# TODO: print the customers with no ordersHint 1
max(find_values(customer, "date"), default="none") handles customers with no orders.
Hint 2
group_by uses groups.setdefault(key(record), []).append(record).
Hint 3
Group once with key=lambda c: c["plan"], then call top_n(group, key=total_spend) for each plan.
Solution
import json
with open("data/customers.json", encoding="utf-8") as f: data = json.load(f)customers = data["customers"]
def find_values(obj, key): """Return every value stored under key, at any depth of dicts and lists.""" found = [] if isinstance(obj, dict): for k, value in obj.items(): if k == key: found.append(value) found.extend(find_values(value, key)) elif isinstance(obj, list): for item in obj: found.extend(find_values(item, key)) return found
def total_spend(customer): """Return the sum of the customer's order amounts, rounded to cents.""" return round(sum(find_values(customer, "amount")), 2)
def last_order(customer): """Return the latest order date as ISO text, or "none".""" return max(find_values(customer, "date"), default="none")
def group_by(records, key): """Return a dict of key(record) -> list of records, in first-seen order.""" groups = {} for record in records: groups.setdefault(key(record), []).append(record) return groups
def top_n(records, n=2, *, key): """Return the n records with the largest key(record), largest first.""" return sorted(records, key=key, reverse=True)[:n]
by_plan = group_by(customers, key=lambda c: c["plan"])for plan in ("basic", "standard", "premium"): group = by_plan[plan] print(f"{plan} ({len(group)} customers)") for c in top_n(group, key=total_spend): print( f" {c['customer_id']} {c['name']:<13} {total_spend(c):>9,.2f} USD" f" signup {c['signup_date']} last order {last_order(c)}" )no_orders = [c["customer_id"] for c in customers if last_order(c) == "none"]print("no orders:", ", ".join(no_orders))
assert total_spend(customers[0]) == 1325.54assert sum(len(g) for g in by_plan.values()) == 20assert top_n(by_plan["basic"], n=1, key=total_spend)[0]["customer_id"] == "C00017"assert no_orders == ["C00008", "C00012", "C00013"]basic (7 customers) C00017 Mateo Lopez 2,324.98 USD signup 2018-12-02 last order 2024-10-11 C00015 Omar Farouk 1,365.28 USD signup 2018-12-02 last order 2024-04-07standard (7 customers) C00019 Ravi Patel 1,763.46 USD signup 2018-12-02 last order 2023-06-03 C00002 James Okafor 961.89 USD signup 2018-12-01 last order 2024-11-27premium (6 customers) C00003 Mei Chen 2,070.07 USD signup 2018-12-01 last order 2024-12-05 C00001 Ana Silva 1,325.54 USD signup 2018-12-01 last order 2023-12-21no orders: C00008, C00012, C00013How it works:
find_valuesdoes the recursive work twice: once foramountand once fordate. A customer with no orders gives empty lists, sosumreturns 0 andmax(..., default="none")returns the marker.group_bytakes a key function, likesorted(). Grouping once and ranking inside each group avoids filtering the whole list once per plan.top_nhasnwith a default and a required keyword-onlykey, so a call readstop_n(group, key=total_spend).- C00019 shows 2023-06-03 as the last order, but the export keeps only the first five orders of each customer, and C00019 has five. Check what a data export contains before you call a customer inactive.
Alternative: pandas does the same with pd.json_normalize(customers, record_path="orders", meta=["customer_id", "plan"]), then groupby("plan") and nlargest (modules 24 and 25). The plain-function version needs no library and each function is easy to test.
M05-X03 · Refactor: a copy-paste sensor report
Section titled “M05-X03 · Refactor: a copy-paste sensor report”Refactor: this script reports the first six temperatures of three sensors from data/sensors.csv (2024-05-01, 00:00 to 00:50). The same five lines are copied three times, and one copy has a bug. Rewrite it with a function report_line(sensor_id, readings, *, digits=2) and a loop. The correct report is the expected output.
s1 = [20.21, 20.22, 20.16, 19.93, 19.9, 20.12]s2 = [22.3, 22.44, 22.25, 22.39, 38.03, 21.95]s3 = [19.4, 19.46, 19.54, 19.43, 19.11, 19.25]
mean1 = sum(s1) / len(s1)spread1 = max(s1) - min(s1)print(f"S1 mean {mean1:.2f} spread {spread1:.2f}")mean2 = sum(s2) / len(s2)spread2 = max(s2) - min(s2)print(f"S2 mean {mean2:.2f} spread {spread2:.2f}")mean3 = sum(s3) / len(s3)spread3 = max(s3) - min(s2)print(f"S3 mean {mean3:.2f} spread {spread3:.2f}")S1 mean 20.09 spread 0.32S2 mean 24.89 spread 16.08S3 mean 19.36 spread -2.41The S2 reading of 38.03 is one of the injected temperature spikes. Add a flag SPIKE to a line when its spread is above a max_spread threshold of 5.0, which the caller passes by keyword.
S1 mean 20.09 spread 0.32S2 mean 24.89 spread 16.08 SPIKES3 mean 19.36 spread 0.43sensors = { "S1": [20.21, 20.22, 20.16, 19.93, 19.9, 20.12], "S2": [22.3, 22.44, 22.25, 22.39, 38.03, 21.95], "S3": [19.4, 19.46, 19.54, 19.43, 19.11, 19.25],}
# TODO: define report_line(sensor_id, readings, *, digits=2, max_spread=None)# TODO: loop over sensors and print one line each, with max_spread=5.0Hint 1
Find the bug first: compare the three spread lines character by character.
Hint 2
The format precision can come from the parameter: f"{mean:.{digits}f}".
Hint 3
max_spread=None means “no check”. Add the flag only when max_spread is not None and spread > max_spread.
Solution
sensors = { "S1": [20.21, 20.22, 20.16, 19.93, 19.9, 20.12], "S2": [22.3, 22.44, 22.25, 22.39, 38.03, 21.95], "S3": [19.4, 19.46, 19.54, 19.43, 19.11, 19.25],}
def report_line(sensor_id, readings, *, digits=2, max_spread=None): """Return a one-line summary of readings.
Args: sensor_id: The id shown at the start of the line. readings: A non-empty list of temperatures in °C. digits: Decimal places for the mean and the spread. max_spread: If given, add "SPIKE" when max - min is above it.
Returns: The report line. """ mean = sum(readings) / len(readings) spread = max(readings) - min(readings) line = f"{sensor_id} mean {mean:.{digits}f} spread {spread:.{digits}f}" if max_spread is not None and spread > max_spread: line += " SPIKE" return line
for sensor_id, readings in sensors.items(): print(report_line(sensor_id, readings, max_spread=5.0))
assert report_line("S1", sensors["S1"]) == "S1 mean 20.09 spread 0.32"assert report_line("S3", sensors["S3"], digits=1) == "S3 mean 19.4 spread 0.4"assert "SPIKE" not in report_line("S2", sensors["S2"])S1 mean 20.09 spread 0.32S2 mean 24.89 spread 16.08 SPIKES3 mean 19.36 spread 0.43How it works:
- The bug was
min(s2)in the S3 line, a classic copy-paste error. It gave S3 a negative spread. With one function, the formula exists once and cannot drift between copies. - The dict maps each sensor id to its readings, so one loop replaces three blocks.
digitsandmax_spreadare keyword-only options with defaults. The defaultNonemeans “do not check”, so the third assert shows that the flag appears only when the caller asks for it.- The function returns the line and does not print it, so the asserts can test it.
Alternative: return the numbers instead of a string, for example a dict from a summarize function, and format in a second function. Split computing from formatting when other code (a chart, a CSV export) needs the same numbers.
M05-X04 · A streaming moving average
Section titled “M05-X04 · A streaming moving average”A moving average is the mean of the last window values. It smooths noisy sensor data. Write make_moving_average(window), a factory that returns a function add(value). Each call stores the value and returns the mean of the last window values (fewer at the start). Feed it the first eight readings of data/readings.txt with a window of 3. Print each reading next to the moving average, rounded to 2 decimals.
21.0 21.00 21.9 21.45 21.4 21.43 21.7 21.67 22.1 21.73 22.0 21.93 22.5 22.20 22.9 22.47readings = [21.0, 21.9, 21.4, 21.7, 22.1, 22.0, 22.5, 22.9]
# TODO: define make_moving_average(window); the closure keeps the recent values# TODO: create one with window=3 and print each reading and its moving averageHint 1
Keep a list recent = [] in the factory. The inner function appends to it.
Hint 2
When the list is longer than window, drop the oldest value with recent.pop(0). Appending and popping change the list, so you do not need nonlocal.
Solution
readings = [21.0, 21.9, 21.4, 21.7, 22.1, 22.0, 22.5, 22.9]
def make_moving_average(window): """Return add(value), which returns the mean of the last window values.""" recent = []
def add(value): recent.append(value) if len(recent) > window: recent.pop(0) return sum(recent) / len(recent)
return add
smooth = make_moving_average(3)averages = []for r in readings: averages.append(smooth(r)) print(f"{r:5.1f} {averages[-1]:6.2f}")
assert averages[0] == 21.0assert round(averages[2], 2) == round((21.0 + 21.9 + 21.4) / 3, 2)other = make_moving_average(2)assert other(10) == 10 and other(20) == 15 and other(30) == 25 21.0 21.00 21.9 21.45 21.4 21.43 21.7 21.67 22.1 21.73 22.0 21.93 22.5 22.20 22.9 22.47How it works:
recentlives in the factory’s scope. Eachaddcall changes the list in place, so the namerecentis never reassigned and nononlocalis needed.- After the third value,
pop(0)removes the oldest one, so the list never holds more thanwindowvalues. - The first two averages use 1 and 2 values. After that, each average uses exactly 3.
- The moving average rises more smoothly than the raw readings: the jump from 21.0 to 21.9 shows up as a rise of 0.45.
Alternative: collections.deque(maxlen=window) (module 09) drops the oldest item by itself and is faster than pop(0) on long windows. pandas has Series.rolling(3).mean() for whole columns (module 25).
M05-X05 · Validate a config against a schema
Section titled “M05-X05 · Validate a config against a schema”A pipeline should refuse to start with a bad config. Write a recursive validate(config, schema, path="") that returns a list of problems. schema mirrors the config: a nested dict whose leaves are the expected types. Report a missing key and a wrong type, with the dotted path. Check the real data/config.json (no problems), then a broken copy. Watch out: in Python, True is also an int.
config: OKbroken: output.overwrite: missingbroken: thresholds.max_quantity: expected int, got strbroken: model.params.max_iter: expected int, got boolimport copyimport json
with open("data/config.json", encoding="utf-8") as f: config = json.load(f)
schema = { "project": str, "output": {"dir": str, "overwrite": bool}, "thresholds": {"min_quantity": int, "max_quantity": int, "max_discount": float}, "model": {"test_size": float, "params": {"C": float, "max_iter": int}}, "retry": {"attempts": int},}
broken = copy.deepcopy(config)broken["thresholds"]["max_quantity"] = "50"broken["model"]["params"]["max_iter"] = Truedel broken["output"]["overwrite"]
# TODO: define validate(config, schema, path="")# TODO: print the problems for config and for brokenHint 1
Loop over schema.items(). For each key, build the dotted path, then check that the key exists in config.
Hint 2
If the expected value is a dict, recurse with config[key], the sub-schema and the new path. Otherwise compare types.
Hint 3
isinstance(True, int) is True, because bool is a subtype of int. Use type(value) is expected to reject a bool where an int is expected.
Solution
import copyimport json
with open("data/config.json", encoding="utf-8") as f: config = json.load(f)
schema = { "project": str, "output": {"dir": str, "overwrite": bool}, "thresholds": {"min_quantity": int, "max_quantity": int, "max_discount": float}, "model": {"test_size": float, "params": {"C": float, "max_iter": int}}, "retry": {"attempts": int},}
broken = copy.deepcopy(config)broken["thresholds"]["max_quantity"] = "50"broken["model"]["params"]["max_iter"] = Truedel broken["output"]["overwrite"]
def validate(config, schema, path=""): """Return a list of problems where config does not match schema.
Args: config: Parsed JSON, a dict. schema: The same shape as config, with expected types as leaves. path: The dotted path of config inside the whole document.
Returns: A list of "path: problem" strings; empty when config is valid. """ problems = [] for key, expected in schema.items(): where = f"{path}.{key}" if path else key if not isinstance(config, dict) or key not in config: problems.append(f"{where}: missing") continue value = config[key] if isinstance(expected, dict): # recursive case: a nested section problems.extend(validate(value, expected, where)) elif type(value) is not expected: # base case: compare the leaf type got = type(value).__name__ problems.append(f"{where}: expected {expected.__name__}, got {got}") return problems
print("config:", validate(config, schema) or "OK")for problem in validate(broken, schema): print("broken:", problem)
assert validate(config, schema) == []assert len(validate(broken, schema)) == 3assert validate({}, {"a": {"b": int}}) == ["a: missing"]config: OKbroken: output.overwrite: missingbroken: thresholds.max_quantity: expected int, got strbroken: model.params.max_iter: expected int, got boolHow it works:
- The schema drives the walk: the function visits exactly the keys that matter and ignores extra keys in the config.
- A dict in the schema is a section, so the function recurses with the matching part of the config and a longer path. Any other schema value is a type, the base case.
type(value) is not expectedis strict.isinstance(True, int)would acceptmax_iter: true, a typo that a model would quietly treat as 1.copy.deepcopycopies every level, so the changes tobrokenleaveconfigintact (shallow vs deep copy, module 04).validate(...) or "OK"printsOKfor an empty list, because an empty list is falsy.
Alternative: in real projects, libraries such as pydantic (module 44) validate configs and API inputs from a class definition. They follow the same idea: a schema, a recursive walk and readable paths in the error messages.