Skip to content

22. Design principles and patterns — Exercises

These exercises practice every idea of the design principles and patterns lesson. They use small slices of data/houses.csv and data/customers.csv, and three exercises read a full data file.

How to work:

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

The setup holds the data slices and the template-method version of minilearn from the lesson, on the APIs of modules 18 to 21: the metrics, Callback, BaseEstimator with fit() → _validate() → _fit(), the mixins, Distance and the distance strategies, Neighbor and five estimators. It prints nothing.

import csv
import inspect
import math
import statistics
from abc import ABC, abstractmethod
from collections import Counter
from collections.abc import Callable, Sequence
from enum import StrEnum, auto
from typing import Any, NamedTuple, Protocol, Self, final, runtime_checkable
type Rows = list[list[float]]
# The first eight houses of data/houses.csv: [sqft] and price.
X_houses: Rows = [
[2420.0],
[1610.0],
[1260.0],
[1790.0],
[3170.0],
[2190.0],
[1680.0],
[1730.0],
]
y_houses = [
1097500.0,
486500.0,
223000.0,
431000.0,
626500.0,
544500.0,
397500.0,
435000.0,
]
# Twenty customers from data/customers.csv (every 250th row):
# [tenure_months, logins_last_30d] and churned (1 = the customer left).
X_cust: Rows = [
[72.0, 17.0],
[69.0, 2.0],
[54.0, 4.0],
[45.0, 2.0],
[39.0, 8.0],
[34.0, 28.0],
[29.0, 15.0],
[26.0, 3.0],
[22.0, 9.0],
[20.0, 8.0],
[17.0, 8.0],
[15.0, 11.0],
[13.0, 13.0],
[11.0, 9.0],
[9.0, 6.0],
[7.0, 11.0],
[6.0, 4.0],
[4.0, 0.0],
[3.0, 17.0],
[1.0, 1.0],
]
y_cust = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1]
# Eight records of data/customers.csv (every 625th row), as csv.DictReader gives them.
RECORDS = [
{
"customer_id": "C00001",
"plan": "premium",
"contract": "two-year",
"tenure_months": "72",
"logins_last_30d": "17",
"churned": "0",
},
{
"customer_id": "C00626",
"plan": "basic",
"contract": "month-to-month",
"tenure_months": "49",
"logins_last_30d": "10",
"churned": "0",
},
{
"customer_id": "C01251",
"plan": "standard",
"contract": "one-year",
"tenure_months": "34",
"logins_last_30d": "28",
"churned": "0",
},
{
"customer_id": "C01876",
"plan": "standard",
"contract": "month-to-month",
"tenure_months": "24",
"logins_last_30d": "10",
"churned": "0",
},
{
"customer_id": "C02501",
"plan": "standard",
"contract": "month-to-month",
"tenure_months": "17",
"logins_last_30d": "8",
"churned": "0",
},
{
"customer_id": "C03126",
"plan": "premium",
"contract": "month-to-month",
"tenure_months": "12",
"logins_last_30d": "8",
"churned": "0",
},
{
"customer_id": "C03751",
"plan": "premium",
"contract": "month-to-month",
"tenure_months": "7",
"logins_last_30d": "11",
"churned": "1",
},
{
"customer_id": "C04376",
"plan": "basic",
"contract": "month-to-month",
"tenure_months": "3",
"logins_last_30d": "14",
"churned": "1",
},
]
def mean_squared_error(y_true: list[float], y_pred: list[float]) -> float:
pairs = list(zip(y_true, y_pred, strict=True))
return sum((t - p) ** 2 for t, p in pairs) / len(pairs)
def r2_score(y_true: list[float], y_pred: list[float]) -> float:
mean = sum(y_true) / len(y_true)
ss_res = sum((t - p) ** 2 for t, p in zip(y_true, y_pred, strict=True))
ss_tot = sum((t - mean) ** 2 for t in y_true)
return 1 - ss_res / ss_tot
def accuracy_score(y_true: list[Any], y_pred: list[Any]) -> float:
return sum(t == p for t, p in zip(y_true, y_pred, strict=True)) / len(y_true)
class NotFittedError(ValueError, AttributeError):
"""Raised when predict() or transform() runs before fit()."""
def check_is_fitted(estimator: object) -> None:
"""Module 21, unchanged: a learned attribute ends with _, not starts with __."""
learned = [k for k in vars(estimator) if k.endswith("_") and not k.startswith("__")]
if not learned:
name = type(estimator).__name__
raise NotFittedError(f"{name} is not fitted yet; call fit() first")
def check_X(X: Sequence[Sequence[float]], owner: str) -> Rows:
if len(X) == 0:
raise ValueError(f"{owner}: X is empty")
width = len(X[0])
for i, row in enumerate(X):
if len(row) != width:
raise ValueError(
f"{owner}: row {i} has length {len(row)}, expected {width}"
)
return [[float(v) for v in row] for row in X]
class Callback:
"""Observer of fit(). Each event does nothing until a subclass overrides it."""
def on_fit_start(self, model: Any, X: Rows, y: list | None) -> None:
"""Called after the input is validated, before the model learns."""
def on_epoch_end(self, model: Any, epoch: int, loss: float) -> None:
"""Called by iterative models after each pass over the data."""
def on_fit_end(self, model: Any) -> None:
"""Called after the model has learned."""
class BaseEstimator(ABC):
"""Parameters, repr, equality and the fit() template."""
_requires_y = True
@classmethod
def _get_param_names(cls) -> list[str]:
params = inspect.signature(cls.__init__).parameters.values()
skip = (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)
return [p.name for p in params if p.name != "self" and p.kind not in skip]
def get_params(self) -> dict[str, Any]:
return {name: getattr(self, name) for name in self._get_param_names()}
def set_params(self, **params: Any) -> Self:
valid = self._get_param_names()
for name, value in params.items():
if name not in valid:
raise ValueError(
f"Invalid parameter {name!r} for {type(self).__name__}"
)
setattr(self, name, value)
return self
def __repr__(self) -> str:
args = ", ".join(f"{k}={v!r}" for k, v in self.get_params().items())
return f"{type(self).__name__}({args})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, BaseEstimator):
return NotImplemented
return type(self) is type(other) and self.get_params() == other.get_params()
@final
def fit(
self, X: Rows, y: list | None = None, *, callbacks: Sequence[Callback] = ()
) -> Self:
rows, labels = self._validate(X, y)
self._callbacks = tuple(callbacks)
self.stop_training = False
for cb in self._callbacks:
cb.on_fit_start(self, rows, labels)
self._fit(rows, labels)
self.n_features_in_ = len(rows[0])
for cb in self._callbacks:
cb.on_fit_end(self)
self._callbacks = ()
return self
def _notify_epoch(self, epoch: int, loss: float) -> None:
for cb in self._callbacks:
cb.on_epoch_end(self, epoch, loss)
def _validate(self, X: Rows, y: list | None) -> tuple[Rows, list | None]:
name = type(self).__name__
rows = check_X(X, name)
if y is None:
if self._requires_y:
raise ValueError(f"{name}.fit() needs y")
return rows, None
if len(y) != len(rows):
raise ValueError(f"{name}: X has {len(rows)} rows but y has {len(y)}")
return rows, list(y)
def _check_input(self, X: Rows) -> Rows:
check_is_fitted(self)
name = type(self).__name__
rows = check_X(X, name)
if len(rows[0]) != self.n_features_in_:
raise ValueError(
f"{name}: X has {len(rows[0])} features, "
f"but fit() saw {self.n_features_in_}"
)
return rows
@abstractmethod
def _fit(self, X: Rows, y: list | None) -> None:
"""The hook: learn from validated data and set attributes ending in _."""
class TransformerMixin:
_requires_y = False
def transform(self, X: Rows) -> Rows:
return self._transform(self._check_input(X))
def fit_transform(
self, X: Rows, y: list | None = None, *, callbacks: Sequence[Callback] = ()
) -> Rows:
return self.fit(X, y, callbacks=callbacks).transform(X)
class PredictorMixin:
def predict(self, X: Rows) -> list:
return self._predict(self._check_input(X))
class RegressorMixin(PredictorMixin):
def score(self, X: Rows, y: list[float]) -> float:
return r2_score(y, self.predict(X))
class ClassifierMixin(PredictorMixin):
def score(self, X: Rows, y: list) -> float:
return accuracy_score(y, self.predict(X))
type Row = Sequence[float]
type DistanceFunc = Callable[[Row, Row], float]
def manhattan(a: Row, b: Row) -> float:
return sum(abs(x - y) for x, y in zip(a, b, strict=True))
class Distance(StrEnum): # module 21
EUCLIDEAN = auto()
MANHATTAN = auto()
def __repr__(self) -> str:
return f"{type(self).__name__}.{self.name}"
DISTANCES: dict[str, DistanceFunc] = {"euclidean": math.dist, "manhattan": manhattan}
def get_distance(distance: Distance | str | DistanceFunc) -> DistanceFunc:
if callable(distance):
return distance
try:
return DISTANCES[distance]
except KeyError:
valid = ", ".join(sorted(DISTANCES))
msg = f"unknown distance {distance!r}; use one of: {valid}"
raise ValueError(msg) from None
class Neighbor(NamedTuple): # module 21
index: int
distance: float
label: Any
class StandardScaler(TransformerMixin, BaseEstimator):
def __init__(self, with_mean: bool = True, with_std: bool = True) -> None:
self.with_mean = with_mean
self.with_std = with_std
def _fit(self, X: Rows, y: list | None) -> None:
columns = list(zip(*X, strict=True))
self.mean_ = [statistics.fmean(c) if self.with_mean else 0.0 for c in columns]
self.scale_ = [
(statistics.pstdev(c) or 1.0) if self.with_std else 1.0 for c in columns
]
def _transform(self, X: Rows) -> Rows:
return [
[(v - m) / s for v, m, s in zip(row, self.mean_, self.scale_, strict=True)]
for row in X
]
class LinearRegression(RegressorMixin, BaseEstimator):
def __init__(self, fit_intercept: bool = True) -> None:
self.fit_intercept = fit_intercept
def _fit(self, X: Rows, y: list[float]) -> None:
x = [row[0] for row in X]
mean_x = statistics.fmean(x) if self.fit_intercept else 0.0
mean_y = statistics.fmean(y) if self.fit_intercept else 0.0
sxy = sum((a - mean_x) * (b - mean_y) for a, b in zip(x, y, strict=True))
sxx = sum((a - mean_x) ** 2 for a in x)
self.coef_ = sxy / sxx
self.intercept_ = mean_y - self.coef_ * mean_x
def _predict(self, X: Rows) -> list[float]:
return [self.intercept_ + self.coef_ * row[0] for row in X]
class MeanRegressor(RegressorMixin, BaseEstimator):
def _fit(self, X: Rows, y: list[float]) -> None:
self.mean_ = statistics.fmean(y)
def _predict(self, X: Rows) -> list[float]:
return [self.mean_ for _ in X]
class MajorityClassifier(ClassifierMixin, BaseEstimator):
def _fit(self, X: Rows, y: list) -> None:
counts = Counter(y)
top = max(counts.values())
self.majority_ = min(label for label, n in counts.items() if n == top)
def _predict(self, X: Rows) -> list:
return [self.majority_ for _ in X]
class KNNClassifier(ClassifierMixin, BaseEstimator):
def __init__(
self,
n_neighbors: int = 5,
distance: Distance | str | DistanceFunc = Distance.EUCLIDEAN,
) -> None:
self.n_neighbors = n_neighbors
self.distance = distance # stored unchanged; resolved in _fit()
def _fit(self, X: Rows, y: list) -> None:
if self.n_neighbors < 1:
raise ValueError(f"n_neighbors must be >= 1, got {self.n_neighbors}")
self.distance_ = get_distance(self.distance)
self.X_train_ = X
self.y_train_ = y
self.classes_ = sorted(set(y))
def kneighbors(self, row: Row) -> list[Neighbor]:
check_is_fitted(self)
pairs = zip(self.X_train_, self.y_train_, strict=True)
found = [
Neighbor(i, self.distance_(row, x), label)
for i, (x, label) in enumerate(pairs)
]
found.sort(key=lambda n: (n.distance, n.index)) # ties: lower row number
return found[: self.n_neighbors]
def _predict(self, X: Rows) -> list:
votes = [Counter(n.label for n in self.kneighbors(row)) for row in X]
return [max(self.classes_, key=lambda label: v[label]) for v in votes]
Warm-up

Write a function chebyshev(a, b) that returns the largest absolute difference between the coordinates of two rows. Then use it, math.dist and manhattan as strategies for the function nearest() in the starter, and print which of the three candidate customers (rows of [tenure_months, logins_last_30d]) is nearest to the new customer [10.0, 5.0] under each distance. Do not change nearest().

Expected output
dist nearest: candidate 1
manhattan nearest: candidate 1
chebyshev nearest: candidate 1
chebyshev to candidate 2: 8.0
Starter
def nearest(row: list[float], candidates: Rows, metric: DistanceFunc) -> int:
return min(range(len(candidates)), key=lambda i: metric(row, candidates[i]))
candidates = [[13.0, 13.0], [9.0, 6.0], [2.0, 4.0]]
new_customer = [10.0, 5.0]
# TODO: write chebyshev(a, b)
# TODO: for each distance, print its name and the index of the nearest candidate
Hint 1

Pair the coordinates with zip(a, b, strict=True), take the absolute difference of each pair, and keep the largest one.

Hint 2

Loop over (math.dist, manhattan, chebyshev) and pass each function, without calling it, as metric=. function.__name__ gives its name.

Solution
def nearest(row: list[float], candidates: Rows, metric: DistanceFunc) -> int:
return min(range(len(candidates)), key=lambda i: metric(row, candidates[i]))
def chebyshev(a: Sequence[float], b: Sequence[float]) -> float:
return max(abs(x - y) for x, y in zip(a, b, strict=True))
candidates = [[13.0, 13.0], [9.0, 6.0], [2.0, 4.0]]
new_customer = [10.0, 5.0]
results = {}
for metric in (math.dist, manhattan, chebyshev):
results[metric.__name__] = nearest(new_customer, candidates, metric)
print(f"{metric.__name__:<10} nearest: candidate {results[metric.__name__]}")
print("chebyshev to candidate 2:", chebyshev(new_customer, candidates[2]))
assert results == {"dist": 1, "manhattan": 1, "chebyshev": 1}
assert chebyshev([0, 0], [3, 4]) == 4
Output
dist nearest: candidate 1
manhattan nearest: candidate 1
chebyshev nearest: candidate 1
chebyshev to candidate 2: 8.0

How it works:

  1. nearest() is the context of the strategy pattern. It calls metric(row, candidate) and does not care which function it holds.
  2. chebyshev takes the largest coordinate difference. For candidate 2, the tenure differs by 8 and the logins by 1, so the distance is 8.
  3. All three distances agree here: candidate 1 differs by only 1 in each feature. On other data they can disagree, as the lesson showed.
  4. No line of nearest() changed. A new distance is a new function (open/closed principle).

Alternative: store the strategies in a dict, DISTANCES["chebyshev"] = chebyshev, and look them up by name. That form suits a config file; the function form suits code.

M22-W02 · Predict the output: aggregation strategies

Section titled “M22-W02 · Predict the output: aggregation strategies”
Warm-up

Predict the output: a sensor report chooses its aggregation by name from a dict of strategies. Read the code and write down the five lines it prints. Then run it.

Acceptance criteria:

  • Write your prediction line by line before you run the code.
  • Your prediction matches the Output in the solution, including the error message on the last line.
Starter
readings = [21.5, 22.0, 19.8, 23.1, 22.0]
AGGREGATIONS = {
"mean": statistics.fmean,
"max": max,
"count": len,
"mode": statistics.mode,
}
for name in ("mean", "max", "count", "mode"):
print(name, round(AGGREGATIONS[name](readings), 2))
try:
AGGREGATIONS["median"](readings)
except KeyError as err:
print("unknown:", err)
Hint 1

Each dict value is a function. AGGREGATIONS[name] looks it up, and (readings) calls it.

Hint 2

statistics.mode returns the most common value. round() of an int returns the same int. A KeyError prints its key with quotes.

Solution
readings = [21.5, 22.0, 19.8, 23.1, 22.0]
AGGREGATIONS = {
"mean": statistics.fmean,
"max": max,
"count": len,
"mode": statistics.mode,
}
results = {}
for name in ("mean", "max", "count", "mode"):
results[name] = round(AGGREGATIONS[name](readings), 2)
print(name, results[name])
try:
AGGREGATIONS["median"](readings)
except KeyError as err:
print("unknown:", err)
assert results == {"mean": 21.68, "max": 23.1, "count": 5, "mode": 22.0}
Output
mean 21.68
max 23.1
count 5
mode 22.0
unknown: 'median'

How it works:

  1. The mean of the five readings is 108.4 / 5 = 21.68.
  2. max and len are built-in functions, so they work as strategies too. len returns the int 5, and round(5, 2) keeps it an int.
  3. 22.0 appears twice, so statistics.mode returns it.
  4. "median" is not a key, so the lookup raises KeyError, and str(err) is the key in quotes: 'median'.

Alternative: AGGREGATIONS.get(name) returns None for an unknown name. A factory that raises a ValueError listing the valid names, as make_model() does in the lesson, gives the user a better message.

M22-W03 · Register models with a decorator

Section titled “M22-W03 · Register models with a decorator”
Warm-up

Write a registry MODELS, a decorator factory register(name) and a factory make_model(name, **params). Register MeanRegressor under "mean" and LinearRegression under "linear" by calling the decorator on the existing classes. Then define a new class MedianRegressor with the @register("median") line. Build each model by name, fit it on the eight houses and print its R².

Expected output
['linear', 'mean', 'median']
LinearRegression(fit_intercept=True) R² 0.407
MeanRegressor() R² 0.000
MedianRegressor() R² -0.083
Starter
MODELS: dict[str, type] = {}
# TODO: register(name) returns a decorator that stores the class and returns it
# TODO: make_model(name, **params) builds a fresh object
# TODO: register MeanRegressor and LinearRegression; define MedianRegressor with @register
# TODO: print the sorted names, then each model's R² on X_houses, y_houses
Hint 1

A decorator factory is a function that returns a function: def register(name): def decorator(cls): ...; return decorator.

Hint 2

register("mean")(MeanRegressor) applies the decorator to a class that already exists. MedianRegressor needs only _fit() and _predict(): the template in the setup does the rest.

Solution
MODELS: dict[str, type] = {}
def register(name: str) -> Callable[[type], type]:
def decorator(cls: type) -> type:
MODELS[name] = cls
return cls
return decorator
def make_model(name: str, **params: Any) -> Any:
return MODELS[name](**params)
register("mean")(MeanRegressor)
register("linear")(LinearRegression)
@register("median")
class MedianRegressor(RegressorMixin, BaseEstimator):
def _fit(self, X: Rows, y: list[float]) -> None:
self.median_ = statistics.median(y)
def _predict(self, X: Rows) -> list[float]:
return [self.median_ for _ in X]
print(sorted(MODELS))
scores = {}
for name in sorted(MODELS):
model = make_model(name).fit(X_houses, y_houses)
scores[name] = model.score(X_houses, y_houses)
print(f"{model!r:<36} R² {scores[name]:.3f}")
assert make_model("median") is not make_model("median") # fresh objects
assert MODELS["median"] is MedianRegressor # the decorator returned the class
assert scores["linear"] > scores["mean"] > scores["median"]
Output
['linear', 'mean', 'median']
LinearRegression(fit_intercept=True) R² 0.407
MeanRegressor() R² 0.000
MedianRegressor() R² -0.083

How it works:

  1. register("median") runs first and returns decorator. Python then calls decorator(MedianRegressor), which stores the class and returns it, so the name MedianRegressor still refers to the class.
  2. make_model() calls the class with the parameters, so every call returns a new object.
  3. The mean baseline has R² exactly 0 on its own training data, by the definition of R². The median scores below 0, because the median is not the value that minimizes squared errors.
  4. The scores are on the training rows, so they only check that the code runs. Real comparisons use a test split.

Alternative: in a package, put @register("...") on every class definition, and import each module in __init__.py so that the decorators run.

M22-W04 · Fix the bug: one model for every experiment

Section titled “M22-W04 · Fix the bug: one model for every experiment”
Warm-up

Fix the bug: this registry stores model objects instead of classes. Two experiments each “build” a KNN model and fit it on different data, but the first experiment’s model changes when the second one trains. Fix the registry so that each call returns a new model. Print the predictions of both experiments, then first is second and first == second.

Expected output
['low'] ['cold']
False True
Starter
MODELS = {"knn": KNNClassifier(n_neighbors=1)}
def make_model(name: str) -> Any:
return MODELS[name]
first = make_model("knn").fit([[0.0], [10.0]], ["low", "high"])
second = make_model("knn").fit([[0.0], [10.0]], ["cold", "hot"])
print(first.predict([[1.0]]), second.predict([[1.0]]))
# TODO: fix MODELS and make_model so that first keeps "low"
Hint 1

Run the starter. Both models print the same labels. Check first is second.

Hint 2

Store the class and its default parameters, for example {"knn": (KNNClassifier, {"n_neighbors": 1})}, and create the object inside make_model().

Solution
MODELS: dict[str, tuple[type, dict[str, Any]]] = {
"knn": (KNNClassifier, {"n_neighbors": 1}),
}
def make_model(name: str, **params: Any) -> Any:
cls, defaults = MODELS[name]
return cls(**(defaults | params)) # a new object on every call
first = make_model("knn").fit([[0.0], [10.0]], ["low", "high"])
second = make_model("knn").fit([[0.0], [10.0]], ["cold", "hot"])
print(first.predict([[1.0]]), second.predict([[1.0]]))
print(first is second, first == second)
assert first.predict([[1.0]]) == ["low"]
assert first is not second
Output
['low'] ['cold']
False True

How it works:

  1. In the starter, the dict holds one KNNClassifier object. make_model() returns that same object twice, so the second fit() overwrote the training data of the first.
  2. The fixed registry holds the class and its default parameters. make_model() calls the class, so each experiment gets its own object.
  3. defaults | params merges two dicts (Python 3.9+): the caller’s parameters win.
  4. first == second is True, because BaseEstimator.__eq__ compares the class and the parameters, not the learned data. is compares identity.

Alternative: register only the class, and give the defaults in its __init__. That is the form of the lesson’s make_model().

M22-W05 · Write an observer that tracks the best epoch

Section titled “M22-W05 · Write an observer that tracks the best epoch”
Warm-up

The training loop train() in the starter calls on_epoch_end(epoch, loss) on every callback. Write a callback BestLoss that remembers the lowest loss and the epoch where it happened, and run it together with the given PrintLoss. Do not change train().

Expected output
epoch 1: loss 0.92
epoch 2: loss 0.61
epoch 3: loss 0.48
epoch 4: loss 0.51
epoch 5: loss 0.47
epoch 6: loss 0.49
best loss 0.47 at epoch 5
Starter
class EpochCallback:
def on_epoch_end(self, epoch: int, loss: float) -> None:
"""Do nothing by default."""
class PrintLoss(EpochCallback):
def on_epoch_end(self, epoch: int, loss: float) -> None:
print(f"epoch {epoch}: loss {loss}")
def train(losses: list[float], callbacks: Sequence[EpochCallback]) -> None:
for epoch, loss in enumerate(losses, start=1): # a recorded run of 6 epochs
for cb in callbacks:
cb.on_epoch_end(epoch, loss)
# TODO: write BestLoss with the attributes best_loss and best_epoch
# TODO: train([0.92, 0.61, 0.48, 0.51, 0.47, 0.49], [PrintLoss(), best]) and print the best
Hint 1

Start best_loss at math.inf, so that any real loss is lower.

Hint 2

In on_epoch_end, compare loss < self.best_loss and update both attributes when it is lower.

Solution
class EpochCallback:
def on_epoch_end(self, epoch: int, loss: float) -> None:
"""Do nothing by default."""
class PrintLoss(EpochCallback):
def on_epoch_end(self, epoch: int, loss: float) -> None:
print(f"epoch {epoch}: loss {loss}")
def train(losses: list[float], callbacks: Sequence[EpochCallback]) -> None:
for epoch, loss in enumerate(losses, start=1):
for cb in callbacks:
cb.on_epoch_end(epoch, loss)
class BestLoss(EpochCallback):
def __init__(self) -> None:
self.best_loss = math.inf
self.best_epoch = 0
def on_epoch_end(self, epoch: int, loss: float) -> None:
if loss < self.best_loss:
self.best_loss, self.best_epoch = loss, epoch
best = BestLoss()
train([0.92, 0.61, 0.48, 0.51, 0.47, 0.49], [PrintLoss(), best])
print(f"best loss {best.best_loss} at epoch {best.best_epoch}")
assert (best.best_loss, best.best_epoch) == (0.47, 5)
Output
epoch 1: loss 0.92
epoch 2: loss 0.61
epoch 3: loss 0.48
epoch 4: loss 0.51
epoch 5: loss 0.47
epoch 6: loss 0.49
best loss 0.47 at epoch 5

How it works:

  1. train() is the subject. It knows only the event name on_epoch_end, not what each callback does.
  2. BestLoss keeps state between events: the lowest loss so far and its epoch.
  3. The loss rises at epoch 4 and falls again at epoch 5, so the best epoch is 5, not the last one. A “save the best model” callback in Keras or Lightning uses exactly this logic.

Alternative: a plain function works as an observer when there is only one event: train(losses, [lambda e, l: print(e, l)]), with cb(epoch, loss) in the loop. The base class pays off when there are several events.

M22-W06 · Chain calls with a fluent builder

Section titled “M22-W06 · Chain calls with a fluent builder”
Warm-up

Write a ReportBuilder for a store report. title(text) sets the title, line(label, value) adds one line, and build() returns the finished text. title() and line() return self, so the calls chain. build() raises ValueError if no title was set. Build the report below in one chained expression.

Expected output
Store S01 daily report
----------------------
Orders 3
Revenue 458.94
error: a report needs a title
Starter
class ReportBuilder:
def __init__(self) -> None:
self._title: str | None = None
self._lines: list[str] = []
# TODO: title(text) -> Self, line(label, value) -> Self, build() -> str
# TODO: build and print the report for store S01 with 3 orders and revenue 458.94
Hint 1

Each method that adds something ends with return self.

Hint 2

Format each line with f"{label:<10}{value:>10}", and underline the title with "-" * len(title).

Solution
class ReportBuilder:
def __init__(self) -> None:
self._title: str | None = None
self._lines: list[str] = []
def title(self, text: str) -> Self:
self._title = text
return self
def line(self, label: str, value: object) -> Self:
self._lines.append(f"{label:<10}{value!s:>10}")
return self
def build(self) -> str:
if self._title is None:
raise ValueError("a report needs a title")
return "\n".join([self._title, "-" * len(self._title), *self._lines])
report = (
ReportBuilder()
.title("Store S01 daily report")
.line("Orders", 3)
.line("Revenue", f"{458.94:,.2f}")
.build()
)
print(report)
try:
ReportBuilder().line("Orders", 3).build()
except ValueError as err:
print("error:", err)
assert report.splitlines()[1] == "-" * 22
Output
Store S01 daily report
----------------------
Orders 3
Revenue 458.94
error: a report needs a title

How it works:

  1. title() and line() change the builder and return it, so the next method is called on the same object. This is a fluent interface.
  2. The parentheses around the chain let it span several lines without backslashes.
  3. build() checks the result before it hands it over. A report without a title is caught at the end of the assembly.
  4. {value!s:>10} converts the value with str() first, so the int 3 and the text "458.94" align the same way.

Alternative: for a report with fixed parts, a function make_report(title, lines) is simpler. The builder pays off when the lines are added in a loop or depend on conditions.

Warm-up

The function summarize() in the starter prints its result, so a test can only check it by capturing the screen. Give it a keyword-only parameter log with the default print. Then call it twice: once with the default, and once with lines.append, and print the collected list.

Expected output
sensor S1: n=3 mean=21.10
['sensor S2: n=2 mean=18.55']
Starter
def summarize(name: str, values: list[float]) -> None:
print(f"{name}: n={len(values)} mean={statistics.fmean(values):.2f}")
# TODO: add the parameter log; call with the default and with lines.append
Hint 1

The signature is def summarize(name, values, *, log=print). Inside, replace print(...) with log(...).

Hint 2

lines.append is a bound method: a function that adds its argument to lines. Pass it without parentheses.

Solution
def summarize(
name: str, values: list[float], *, log: Callable[[str], None] = print
) -> None:
log(f"{name}: n={len(values)} mean={statistics.fmean(values):.2f}")
summarize("sensor S1", [21.5, 22.0, 19.8])
lines: list[str] = []
summarize("sensor S2", [18.2, 18.9], log=lines.append)
print(lines)
assert lines == ["sensor S2: n=2 mean=18.55"]
Output
sensor S1: n=3 mean=21.10
['sensor S2: n=2 mean=18.55']

How it works:

  1. The default print keeps the production call unchanged: summarize("sensor S1", ...) still prints.
  2. The test call passes lines.append, so the text goes into a list that the assert checks exactly.
  3. The * makes log keyword-only. A caller cannot pass it by position by mistake.

Alternative: the standard logging module (module 06) is the production version of this idea: the caller configures handlers, and pytest’s caplog fixture captures the records in tests.

Warm-up

Interpret the code: each description below is a design problem from a data team’s code base. Store, in a dict, the letter of the SOLID principle that each one violates most clearly ("S", "O", "L", "I" or "D"), and print it.

  1. ModelTrainer.train() opens "/data/prod/customers.csv" and creates a SlackClient inside.
  2. export(df, fmt) has an if/elif branch for each of seven file formats, and a new one is added every month.
  3. ChurnPipeline loads data, engineers features, trains, plots charts and emails the report.
  4. BaseStep declares eleven abstract methods; most steps implement six of them as raise NotImplementedError.
  5. RobustScaler.transform() returns a dict of columns, while every other transformer returns a list of rows.

Acceptance criteria:

  • Decide each answer before you open the solution.
  • Your dict matches the one in the solution, and you can say why in one sentence per item.
Starter
answers = {
1: "?", # TODO
2: "?",
3: "?",
4: "?",
5: "?",
}
print(answers)
Hint 1

Ask for each item: is the problem too many jobs (S), editing to extend (O), a broken promise of a subclass (L), a too large interface (I) or a hard-wired detail (D)?

Hint 2

Item 4 and item 5 both involve subclasses. In item 4, the problem is the size of the interface; in item 5, a subclass breaks what callers expect.

Solution
answers = {1: "D", 2: "O", 3: "S", 4: "I", 5: "L"}
for item, letter in answers.items():
print(item, letter)
assert sorted(answers.values()) == ["D", "I", "L", "O", "S"]
Output
1 D
2 O
3 S
4 I
5 L

How it works:

  1. D: the trainer depends on a fixed path and a concrete client. Inject a loader and a notifier.
  2. O: every new format edits a working function. Use a dict of export functions (a registry).
  3. S: five reasons to change in one class. Split it into steps.
  4. I: steps depend on methods they cannot use. Use several small protocols.
  5. L: code that works with any transformer breaks with this one. Keep the return type.

Alternative: items can show more than one violation. Item 3 also probably hard-wires the email server (D). Name the most direct one first, then fix the others one at a time.

M22-C01 · Split a report class by responsibility

Section titled “M22-C01 · Split a report class by responsibility”
Core

Refactor: PlanReport.run() in the starter computes the churn rate per plan from customer records and formats a table, all in one method. Split it into three functions: churn_by(records, column) returns a dict, format_table(rates, title) returns text, and plan_report(records) combines them. Run the new code on RECORDS and also by contract, and check that the plan output equals the old class’s output.

Expected output
Churn by plan
basic 1/2 50%
premium 1/3 33%
standard 0/3 0%
Churn by contract
month-to-month 2/6 33%
one-year 0/1 0%
two-year 0/1 0%
Starter
class PlanReport:
def __init__(self, records: list[dict[str, str]]) -> None:
self.records = records
def run(self) -> str:
counts: dict[str, list[int]] = {}
for rec in self.records:
churned, total = counts.get(rec["plan"], [0, 0])
counts[rec["plan"]] = [churned + int(rec["churned"]), total + 1]
out = ["Churn by plan"]
for plan in sorted(counts):
churned, total = counts[plan]
out.append(f" {plan:<15}{churned}/{total} {churned / total:.0%}")
return "\n".join(out)
old = PlanReport(RECORDS).run()
# TODO: churn_by(records, column) -> dict[str, tuple[int, int]]
# TODO: format_table(rates, title) -> str
# TODO: plan_report(records) -> str; print it and a table by contract
Hint 1

Let churn_by() return {value: (churned, total)}, sorted by value. Then format_table() needs no knowledge of plans or contracts.

Hint 2

plan_report(records) is one line: format_table(churn_by(records, "plan"), "Churn by plan").

Solution
class PlanReport:
def __init__(self, records: list[dict[str, str]]) -> None:
self.records = records
def run(self) -> str:
counts: dict[str, list[int]] = {}
for rec in self.records:
churned, total = counts.get(rec["plan"], [0, 0])
counts[rec["plan"]] = [churned + int(rec["churned"]), total + 1]
out = ["Churn by plan"]
for plan in sorted(counts):
churned, total = counts[plan]
out.append(f" {plan:<15}{churned}/{total} {churned / total:.0%}")
return "\n".join(out)
def churn_by(records: list[dict[str, str]], column: str) -> dict[str, tuple[int, int]]:
groups: dict[str, list[int]] = {}
for rec in records:
groups.setdefault(rec[column], []).append(int(rec["churned"]))
return {key: (sum(flags), len(flags)) for key, flags in sorted(groups.items())}
def format_table(rates: dict[str, tuple[int, int]], title: str) -> str:
rows = [f" {k:<15}{c}/{n} {c / n:.0%}" for k, (c, n) in rates.items()]
return "\n".join([title, *rows])
def plan_report(records: list[dict[str, str]]) -> str:
return format_table(churn_by(records, "plan"), "Churn by plan")
old = PlanReport(RECORDS).run()
new = plan_report(RECORDS)
print(new)
print(format_table(churn_by(RECORDS, "contract"), "Churn by contract"))
assert new == old
assert churn_by([{"plan": "basic", "churned": "1"}], "plan") == {"basic": (1, 1)}
Output
Churn by plan
basic 1/2 50%
premium 1/3 33%
standard 0/3 0%
Churn by contract
month-to-month 2/6 33%
one-year 0/1 0%
two-year 0/1 0%

How it works:

  1. churn_by() holds the computation and nothing else. It takes the column as a parameter, so one function serves plans, contracts and regions.
  2. format_table() holds the layout. A dashboard team can replace it (with HTML, for example) without touching the numbers.
  3. plan_report() keeps the old behavior for existing callers. The assert proves that the refactoring changed nothing.
  4. The last assert tests the computation with one record typed in place: no class and no file needed.

Alternative: keep a class, but give it one job: ChurnTable(column) with a compute(records) method. A function is simpler here, because nothing is stored between calls.

M22-C02 · Replace an if/elif chain with a strategy dict

Section titled “M22-C02 · Replace an if/elif chain with a strategy dict”
Core

Refactor: rescale(values, kind) in the starter grows a branch for each scaling method. Replace the chain with a dict RESCALERS of functions and a short rescale() that looks the function up. An unknown kind must raise ValueError with the sorted list of valid kinds. Then add a fourth method, "max_abs" (divide by the largest absolute value), by adding a function and one dict entry only. Print the four results for the house sizes.

Expected output
minmax [0.61, 0.18, 0.0, 0.28]
zscore [0.79, -0.66, -1.29, -0.34]
none [2420.0, 1610.0, 1260.0, 1790.0]
max_abs [0.76, 0.51, 0.4, 0.56]
unknown kind 'log'; choose from ['max_abs', 'minmax', 'none', 'zscore']
Starter
def rescale(values: list[float], kind: str) -> list[float]:
if kind == "minmax":
lo, hi = min(values), max(values)
return [(v - lo) / (hi - lo) for v in values]
elif kind == "zscore":
m, s = statistics.fmean(values), statistics.pstdev(values)
return [(v - m) / s for v in values]
elif kind == "none":
return list(values)
else:
raise ValueError(kind)
sqft = [row[0] for row in X_houses]
# TODO: RESCALERS dict, a new rescale(), and the new kind "max_abs"
Hint 1

Move each branch into its own function with the signature (values: list[float]) -> list[float].

Hint 2

rescale() becomes a try/except KeyError around RESCALERS[kind], plus the call.

Solution
def minmax(values: list[float]) -> list[float]:
lo, hi = min(values), max(values)
return [(v - lo) / (hi - lo) for v in values]
def zscore(values: list[float]) -> list[float]:
m, s = statistics.fmean(values), statistics.pstdev(values)
return [(v - m) / s for v in values]
def identity(values: list[float]) -> list[float]:
return list(values)
def max_abs(values: list[float]) -> list[float]:
top = max(abs(v) for v in values)
return [v / top for v in values]
RESCALERS: dict[str, Callable[[list[float]], list[float]]] = {
"minmax": minmax,
"zscore": zscore,
"none": identity,
"max_abs": max_abs, # the new kind: one function, one entry
}
def rescale(values: list[float], kind: str) -> list[float]:
try:
func = RESCALERS[kind]
except KeyError:
raise ValueError(
f"unknown kind {kind!r}; choose from {sorted(RESCALERS)}"
) from None
return func(values)
sqft = [row[0] for row in X_houses]
for kind in RESCALERS:
print(f"{kind:<8}", [round(v, 2) for v in rescale(sqft, kind)][:4])
try:
rescale(sqft, "log")
except ValueError as err:
print(err)
assert rescale(sqft, "max_abs")[4] == 1.0
assert rescale([1.0, 3.0], "minmax") == [0.0, 1.0]
Output
minmax [0.61, 0.18, 0.0, 0.28]
zscore [0.79, -0.66, -1.29, -0.34]
none [2420.0, 1610.0, 1260.0, 1790.0]
max_abs [0.76, 0.51, 0.4, 0.56]
unknown kind 'log'; choose from ['max_abs', 'minmax', 'none', 'zscore']

How it works:

  1. Each scaling method is now a function that you can test alone.
  2. rescale() no longer changes when a method is added: it is closed for modification. max_abs needed one function and one dict entry.
  3. The largest house (3,170 sqft, index 4) becomes 1.0 under max_abs.
  4. from None hides the internal KeyError, so the user sees only the helpful ValueError.

Alternative: let rescale() also accept a function: func = kind if callable(kind) else RESCALERS[kind]. Then a caller can pass a one-off method without registering it, as get_distance() does in the setup.

M22-C03 · Fix the bug: a score in percent

Section titled “M22-C03 · Fix the bug: a score in percent”
Core

Fix the bug: PercentLinearRegression reports its R² in percent (40.7 instead of 0.407), because a colleague found it “easier to read”. A model-selection step keeps every model with score >= 0.3 and picks the best. Run the starter on the eight houses: the model without an intercept wins, but only because of its units. Name the broken principle, fix the subclass so that the selection is right, and print each model’s R² as a percentage and the winner.

Expected output
LinearRegression(fit_intercept=True) R² 40.7%
PercentLinearRegression(fit_intercept=False) R² 40.7%
winner: LinearRegression(fit_intercept=True)
Starter
class PercentLinearRegression(LinearRegression):
def score(self, X: Rows, y: list[float]) -> float:
return 100 * r2_score(y, self.predict(X)) # "easier to read"
models = [LinearRegression(), PercentLinearRegression(fit_intercept=False)]
scores = {repr(m): m.fit(X_houses, y_houses).score(X_houses, y_houses) for m in models}
kept = {name: s for name, s in scores.items() if s >= 0.3}
print(scores, "winner:", max(kept, key=kept.get))
# TODO: fix PercentLinearRegression so that the selection works
Hint 1

Every score() in minilearn returns R² or accuracy as a fraction, where 1.0 is perfect. Which SOLID principle says that a subclass must keep its parent’s promises?

Hint 2

Do not override score(). If someone wants percent, add a method with another name, or format the number where it is shown: f"{score:.1%}".

Solution
class PercentLinearRegression(LinearRegression):
"""Fixed: score() keeps the parent's meaning, a fraction where 1.0 is perfect."""
def score_percent(self, X: Rows, y: list[float]) -> float:
return 100 * self.score(X, y) # a new name for a new meaning
models = [LinearRegression(), PercentLinearRegression(fit_intercept=False)]
scores = {repr(m): m.fit(X_houses, y_houses).score(X_houses, y_houses) for m in models}
kept = {name: s for name, s in scores.items() if s >= 0.3}
for name, s in scores.items():
print(f"{name:<45} R² {s:.1%}")
winner = max(kept, key=kept.get)
print("winner:", winner)
assert winner == "LinearRegression(fit_intercept=True)"
assert round(models[1].score_percent(X_houses, y_houses), 1) == round(
100 * scores[repr(models[1])], 1
)
Output
LinearRegression(fit_intercept=True) R² 40.7%
PercentLinearRegression(fit_intercept=False) R² 40.7%
winner: LinearRegression(fit_intercept=True)

How it works:

  1. The bug breaks the Liskov substitution principle: a PercentLinearRegression is a LinearRegression, but its score() means something else. The threshold and max() both assume fractions.
  2. In percent, the weaker model’s score is a number above 1, so it passes any threshold and beats every honest score. No exception warns you.
  3. The fix inherits score() unchanged and adds a separately named method for the new meaning. The display uses the % format spec.
  4. After the fix, both lines score about 40.7%, because the intercept is small next to these prices. The line with an intercept is slightly higher (0.4072 against 0.4069): on its training rows, a least-squares line with an intercept is never worse than one without. Before the fix, the percent model won by a factor of 100, and it would win the same way against any better model. The scores are measured on the training rows here, which is enough to show the bug; a real comparison uses a test split.

Alternative: delete the subclass entirely. A class that only rescales a number is not worth a type: f"{model.score(X, y):.1%}" does it where it is needed.

M22-C04 · Split a fat interface into Protocols

Section titled “M22-C04 · Split a fat interface into Protocols”
Core

Refactor: the abstract class FatStep in the starter forces every pipeline step to implement fit, transform, predict and inverse_transform. Replace it with three small runtime-checkable Protocols: SupportsFit, SupportsTransform and SupportsPredict. Write capabilities(obj), which returns the sorted names of the protocols that an object supports, and print them for StandardScaler(), LinearRegression(), a ClipStep that only has transform(), and the string "scaler".

Expected output
StandardScaler ['fit', 'transform']
LinearRegression ['fit', 'predict']
ClipStep ['transform']
str []
[[0.0, 0.3, 1.0]]
Starter
class FatStep(ABC):
@abstractmethod
def fit(self, X, y=None): ...
@abstractmethod
def transform(self, X): ...
@abstractmethod
def predict(self, X): ...
@abstractmethod
def inverse_transform(self, X): ...
class ClipStep:
"""Clip every value to the range [0, 1]; it learns nothing."""
def transform(self, X: Rows) -> Rows:
return [[min(max(v, 0.0), 1.0) for v in row] for row in X]
# TODO: three Protocols, capabilities(obj), and the five lines of output
Hint 1

A Protocol lists one method: class SupportsTransform(Protocol): def transform(self, X: Rows) -> Rows: .... Add @runtime_checkable so that isinstance() works.

Hint 2

isinstance() with a runtime-checkable Protocol checks only that the methods exist. Loop over a dict {"fit": SupportsFit, ...}.

Solution
@runtime_checkable
class SupportsFit(Protocol):
def fit(self, X: Rows, y: Any = None) -> Any: ...
@runtime_checkable
class SupportsTransform(Protocol):
def transform(self, X: Rows) -> Rows: ...
@runtime_checkable
class SupportsPredict(Protocol):
def predict(self, X: Rows) -> list: ...
class ClipStep:
"""Clip every value to the range [0, 1]; it learns nothing."""
def transform(self, X: Rows) -> Rows:
return [[min(max(v, 0.0), 1.0) for v in row] for row in X]
PROTOCOLS = {
"fit": SupportsFit,
"transform": SupportsTransform,
"predict": SupportsPredict,
}
def capabilities(obj: object) -> list[str]:
return sorted(name for name, proto in PROTOCOLS.items() if isinstance(obj, proto))
for obj in (StandardScaler(), LinearRegression(), ClipStep(), "scaler"):
print(f"{type(obj).__name__:<17} {capabilities(obj)}")
print(ClipStep().transform([[-0.5, 0.3, 1.7]]))
assert capabilities(ClipStep()) == ["transform"]
assert capabilities("scaler") == []
Output
StandardScaler ['fit', 'transform']
LinearRegression ['fit', 'predict']
ClipStep ['transform']
str []
[[0.0, 0.3, 1.0]]

How it works:

  1. Each Protocol describes one ability. ClipStep has no base class and no fit(), yet it counts as a transformer, because it has transform(). This is structural typing (modules 12 and 19).
  2. With FatStep, ClipStep would need three methods that do nothing or raise. With the Protocols, it needs none.
  3. A pipeline can now ask only for what it uses: transformers need transform, the last step needs predict.
  4. isinstance() with a Protocol checks that the methods exist, not their signatures. A type checker such as mypy checks the signatures statically.

Alternative: hasattr(obj, "transform") gives the same answer at run time without Protocols. The Protocols add documentation and static type checking.

Core

Refactor: RetrainJob.run() in the starter reads data/houses.csv itself and prints. Rewrite it as a function retrain(load, model, *, log=print) that receives a loader (a function that returns X and y), a model and a log function, trains on all rows, logs the slope and returns the model. Run it once with a loader for the real file and once with a loader that returns the eight houses of the setup, logging into a list.

Expected output
retrained on 3000 houses: 326.8 USD per sqft
['retrained on 8 houses: 275.1 USD per sqft']
Starter
class RetrainJob:
def run(self) -> None:
with open("data/houses.csv", encoding="utf-8", newline="") as f:
records = list(csv.DictReader(f))
X = [[float(r["sqft"])] for r in records]
y = [float(r["price"]) for r in records]
model = LinearRegression().fit(X, y)
print(f"retrained on {len(X)} houses: {model.coef_:,.1f} USD per sqft")
RetrainJob().run()
# TODO: retrain(load, model, *, log=print); load_houses_csv(); a fake loader
Hint 1

A loader has the type Callable[[], tuple[Rows, list[float]]]. The real one contains the open() code from the starter.

Hint 2

The fake loader can be lambda: (X_houses, y_houses).

Solution
type Loader = Callable[[], tuple[Rows, list[float]]]
def retrain(load: Loader, model: Any, *, log: Callable[[str], None] = print) -> Any:
X, y = load()
model.fit(X, y)
log(f"retrained on {len(X)} houses: {model.coef_:,.1f} USD per sqft")
return model
def load_houses_csv() -> tuple[Rows, list[float]]:
with open("data/houses.csv", encoding="utf-8", newline="") as f:
records = list(csv.DictReader(f))
return [[float(r["sqft"])] for r in records], [float(r["price"]) for r in records]
retrain(load_houses_csv, LinearRegression())
lines: list[str] = []
small = retrain(lambda: (X_houses, y_houses), LinearRegression(), log=lines.append)
print(lines)
assert lines == [f"retrained on 8 houses: {small.coef_:,.1f} USD per sqft"]
assert 0 < small.coef_ < 1000
Output
retrained on 3000 houses: 326.8 USD per sqft
['retrained on 8 houses: 275.1 USD per sqft']

How it works:

  1. The job’s logic (load, fit, log) no longer names a file, a model class or print(). It depends on three abstractions: “a function that returns X and y”, “an object with fit() and coef_”, “a function that takes a string”.
  2. load_houses_csv() holds the detail that RetrainJob hard-coded. It is the production loader.
  3. The second call runs in microseconds on eight rows and collects the log line for an exact assert.
  4. The slope differs between the full file and the eight houses, because a small sample is noisy. That is a fact about the data, not about the design.

Alternative: keep a class and inject through the constructor: RetrainJob(load, model, log).run(). That form suits a job object that a scheduler runs many times with the same collaborators.

M22-C06 · Compare distance strategies with leave-one-out

Section titled “M22-C06 · Compare distance strategies with leave-one-out”
Core

Twenty customers are too few for a train/test split. Leave-one-out evaluation trains on all rows but one, predicts the left-out row, and repeats for every row. Write leave_one_out(make, X, y), where make is a function that returns a fresh model. Use it to compare KNNClassifier(n_neighbors=1) with the distances "euclidean" and "manhattan" and two weighted Euclidean distances, one that multiplies the squared login difference by 4 and one that does the same for tenure, on X_cust. Fit a StandardScaler inside each fold, on the training rows only. Print the accuracy of each, and of MajorityClassifier.

Expected output
majority leave-one-out accuracy 0.80
knn euclidean leave-one-out accuracy 0.60
knn manhattan leave-one-out accuracy 0.50
knn logins x4 leave-one-out accuracy 0.55
knn tenure x4 leave-one-out accuracy 0.65
Starter
# TODO: leave_one_out(make, X, y) -> float (accuracy); scale inside each fold
# TODO: weighted(weights) -> a distance function (a function factory)
# TODO: compare the majority baseline and three KNN strategies
Hint 1

For row i, fit a scaler on X[:i] + X[i + 1:], train on the scaled rows and predict the scaled [X[i]]. Count the correct predictions.

Hint 2

Pass a lambda as make, for example lambda: KNNClassifier(1, distance="manhattan"), so that every fold gets a fresh model.

Hint 3

weighted(weights) returns an inner function distance(a, b) that computes math.sqrt(sum(w * (x - y) ** 2 ...)).

Solution
def leave_one_out(make: Callable[[], Any], X: Rows, y: list) -> float:
hits = 0
for i in range(len(X)):
scaler = StandardScaler().fit(X[:i] + X[i + 1 :]) # training rows only
model = make().fit(scaler.transform(X[:i] + X[i + 1 :]), y[:i] + y[i + 1 :])
hits += model.predict(scaler.transform([X[i]]))[0] == y[i]
return hits / len(X)
def weighted(weights: list[float]) -> DistanceFunc:
def distance(a: Sequence[float], b: Sequence[float]) -> float:
terms = zip(a, b, weights, strict=True)
return math.sqrt(sum(w * (x - y) ** 2 for x, y, w in terms))
return distance
candidates = {
"majority": lambda: MajorityClassifier(),
"knn euclidean": lambda: KNNClassifier(1),
"knn manhattan": lambda: KNNClassifier(1, distance="manhattan"),
"knn logins x4": lambda: KNNClassifier(1, distance=weighted([1.0, 4.0])),
"knn tenure x4": lambda: KNNClassifier(1, distance=weighted([4.0, 1.0])),
}
results = {
name: leave_one_out(make, X_cust, y_cust) for name, make in candidates.items()
}
for name, acc in results.items():
print(f"{name:<14} leave-one-out accuracy {acc:.2f}")
assert results == {
"majority": 0.8,
"knn euclidean": 0.6,
"knn manhattan": 0.5,
"knn logins x4": 0.55,
"knn tenure x4": 0.65,
}
Output
majority leave-one-out accuracy 0.80
knn euclidean leave-one-out accuracy 0.60
knn manhattan leave-one-out accuracy 0.50
knn logins x4 leave-one-out accuracy 0.55
knn tenure x4 leave-one-out accuracy 0.65

How it works:

  1. leave_one_out() receives a factory function, not a model. A fresh model per fold guarantees that nothing learned in one fold carries over to the next. The scaler is fitted inside each fold for the same reason: a scaler fitted on all 20 rows would have seen the left-out row (data leakage).
  2. The strategies differ only in the distance argument. KNNClassifier is unchanged.
  3. weighted([1.0, 4.0]) builds a closure that remembers its weights. It is a strategy with a setting.
  4. Interpretation: with 4 churners among 20 customers, the majority baseline is right 16 times out of 20 (0.80). With one neighbor, each KNN variant copies the label of a single customer and scores 0.50 to 0.65, below the baseline. The variants differ, so the exact asserts would catch a wrong fold or a scaler fitted on all 20 rows. Twenty rows rank strategies only roughly: one prediction changes an accuracy by 0.05.

Alternative: scikit-learn’s cross_val_score(KNeighborsClassifier(3, metric="manhattan"), X, y, cv=LeaveOneOut()) does the same with its own factory: it clones the estimator for each fold (module 37).

M22-C07 · Write a transformer with hooks only

Section titled “M22-C07 · Write a transformer with hooks only”
Core

Write MinMaxScaler(TransformerMixin, BaseEstimator) with only the hooks _fit() (learn min_ and max_ per column) and _transform() (scale each value to 0..1; a constant column becomes 0.0). Do not write fit() or transform(). Fit it on X_cust, show three errors that the template gives you for free: transform before fit, a ragged row, and (after fitting and printing the first two transformed rows) a row with the wrong number of features.

Expected output
NotFittedError: MinMaxScaler is not fitted yet; call fit() first
ValueError: MinMaxScaler: row 1 has length 1, expected 2
[[1.0, 0.607], [0.958, 0.071]]
ValueError: MinMaxScaler: X has 3 features, but fit() saw 2
Starter
class MinMaxScaler(TransformerMixin, BaseEstimator):
# TODO: _fit(self, X, y) sets self.min_ and self.max_
# TODO: _transform(self, X) returns the scaled rows
...
# TODO: fit on X_cust, print 2 rows, then trigger the three errors
Hint 1

columns = list(zip(*X, strict=True)) gives one tuple per feature. self.min_ = [min(c) for c in columns].

Hint 2

Compute span = hi - lo per column and return 0.0 when span == 0. Catch ValueError for each error; NotFittedError is a ValueError too.

Solution
class MinMaxScaler(TransformerMixin, BaseEstimator):
def _fit(self, X: Rows, y: list | None) -> None:
columns = list(zip(*X, strict=True))
self.min_ = [min(c) for c in columns]
self.max_ = [max(c) for c in columns]
def _transform(self, X: Rows) -> Rows:
bounds = list(zip(self.min_, self.max_, strict=True))
return [
[
(v - lo) / (hi - lo) if hi > lo else 0.0
for v, (lo, hi) in zip(row, bounds, strict=True)
]
for row in X
]
scaler = MinMaxScaler()
for bad in (
lambda: scaler.transform(X_cust),
lambda: MinMaxScaler().fit([[1.0, 2.0], [3.0]]),
):
try:
bad()
except ValueError as err:
print(f"{type(err).__name__}: {err}")
scaled = scaler.fit_transform(X_cust)
print([[round(v, 3) for v in row] for row in scaled[:2]])
try:
scaler.transform([[10.0, 5.0, 1.0]])
except ValueError as err:
print(f"{type(err).__name__}: {err}")
assert scaler.min_ == [1.0, 0.0] and scaler.max_ == [72.0, 28.0]
assert scaled[0] == [1.0, 17 / 28]
assert MinMaxScaler().fit([[5.0], [5.0]]).transform([[5.0]]) == [[0.0]]
Output
NotFittedError: MinMaxScaler is not fitted yet; call fit() first
ValueError: MinMaxScaler: row 1 has length 1, expected 2
[[1.0, 0.607], [0.958, 0.071]]
ValueError: MinMaxScaler: X has 3 features, but fit() saw 2

How it works:

  1. The class has two short methods and no checks. fit(), transform() and fit_transform() come from the setup’s base class and mixin.
  2. The template checks that the model is fitted, that the rows have equal length and that the number of features matches fit(). The messages name the class, because the template uses type(self).__name__.
  3. _requires_y = False in TransformerMixin lets fit() work without a y.
  4. A constant column (hi == lo) would divide by zero, so the hook returns 0.0 for it. This is the scaler’s own rule, so it lives in the hook.

Alternative: scikit-learn has no template fit(): its BaseEstimator defines no fit at all. Each estimator writes its own fit(); MinMaxScaler.fit(), for example, resets its state and calls partial_fit(), which validates the input with the shared helper validate_data() under the @_fit_context decorator. The minilearn template is a deliberate simplification of that design. Module 34 builds custom transformers on scikit-learn’s BaseEstimator and TransformerMixin.

M22-C08 · Fix the bug: a subclass that overrides the template

Section titled “M22-C08 · Fix the bug: a subclass that overrides the template”
Core

Fix the bug: NonNegativeRegression should predict like LinearRegression, but never below 0 USD. Its author overrode fit() and predict(). Now a chained fit(...).predict(...) crashes, the FitLogger callback is silent, and the class accepts a ragged row. Rewrite the subclass with hooks only, so that the template does its work again. Show that the logger runs, that predictions are clipped at 0, and that a ragged row is rejected.

Expected output
fit NonNegativeRegression on 8 rows
[0, 535345]
unclipped: -1029
NonNegativeRegression: row 1 has length 2, expected 1
Starter
class FitLogger(Callback):
def on_fit_start(self, model: Any, X: Rows, y: list | None) -> None:
print(f"fit {type(model).__name__} on {len(X)} rows")
class NonNegativeRegression(LinearRegression):
def fit(self, X, y, *, callbacks=()):
x = [row[0] for row in X]
mean_x, mean_y = statistics.fmean(x), statistics.fmean(y)
sxy = sum((a - mean_x) * (b - mean_y) for a, b in zip(x, y, strict=True))
self.coef_ = sxy / sum((a - mean_x) ** 2 for a in x)
self.intercept_ = mean_y - self.coef_ * mean_x
def predict(self, X):
return [max(0.0, self.intercept_ + self.coef_ * row[0]) for row in X]
model = NonNegativeRegression().fit(X_houses, y_houses, callbacks=[FitLogger()])
print(model.predict([[50.0], [2000.0]]))
# TODO: rewrite NonNegativeRegression with hooks only
Hint 1

Run the starter: fit() returns None, so .predict fails with AttributeError. The parent’s _fit() already computes the line.

Hint 2

Override only _predict(): call super()._predict(X) and clip each value with max(0.0, p).

Solution
class FitLogger(Callback):
def on_fit_start(self, model: Any, X: Rows, y: list | None) -> None:
print(f"fit {type(model).__name__} on {len(X)} rows")
class NonNegativeRegression(LinearRegression):
"""Least squares, but predictions never go below 0."""
def _predict(self, X: Rows) -> list[float]:
return [max(0.0, p) for p in super()._predict(X)]
model = NonNegativeRegression().fit(X_houses, y_houses, callbacks=[FitLogger()])
pred = model.predict([[50.0], [2000.0]])
print([round(p) for p in pred])
print(
"unclipped:",
round(LinearRegression().fit(X_houses, y_houses).predict([[50.0]])[0]),
)
try:
NonNegativeRegression().fit([[1500.0], [2000.0, 3.0]], [1.0, 2.0])
except ValueError as err:
print(err)
assert pred[0] == 0.0 and pred[1] > 0
Output
fit NonNegativeRegression on 8 rows
[0, 535345]
unclipped: -1029
NonNegativeRegression: row 1 has length 2, expected 1

How it works:

  1. The starter’s fit() replaced the template, so it lost three things: the validation, the callbacks and return self. The missing return made fit() return None, so the chained .predict() raised AttributeError.
  2. The fixed class inherits _fit() unchanged and overrides only the hook _predict(). super()._predict(X) reuses the parent’s line, and the subclass adds only its own rule.
  3. The parent’s line has a negative intercept, so it predicts a negative price for a 50 sqft parking space. The clipped model returns 0.
  4. The ragged row now fails in the template’s validation, with the class name in the message.

Alternative: a wrapper object (composition) can clip any regressor: Clipped(LinearRegression()) with fit() that delegates and predict() that clips. It works for every model, not only for LinearRegression.

M22-C09 · Early stopping on a validation loss

Section titled “M22-C09 · Early stopping on a validation loss”
Core

The lesson’s EarlyStopping watched the training loss. A training loss keeps falling as long as the model fits the training rows better; the useful signal is the loss on rows the model does not train on. The loop fit_line() in the starter trains on the first six houses and sends both losses to its callbacks. Write BestOnValidation(patience): it remembers the lowest validation loss, its epoch and the coefficients at that epoch; after patience epochs without a new best it puts the best coefficients back into state and sets state["stop"] = True. Train with a learning rate of 0.05 for at most 300 epochs and patience=5, and print the stop epoch, the best epoch and the restored slope.

Expected output
stopped at epoch 27, best epoch 22
best validation loss 141.7; restored coef 154.9
Starter
def fit_line(x_tr, y_tr, x_val, y_val, lr: float, epochs: int, callbacks: list) -> dict:
state = {"coef": 0.0, "intercept": 0.0, "stop": False, "epoch": 0}
n = len(x_tr)
for epoch in range(1, epochs + 1):
err = [state["intercept"] + state["coef"] * a - b for a, b in zip(x_tr, y_tr)]
state["coef"] -= lr * 2 / n * sum(e * a for e, a in zip(err, x_tr))
state["intercept"] -= lr * 2 / n * sum(err)
state["epoch"] = epoch
loss = sum(e * e for e in err) / n
val_err = [
state["intercept"] + state["coef"] * a - b for a, b in zip(x_val, y_val)
]
val_loss = sum(e * e for e in val_err) / len(val_err)
for cb in callbacks:
cb.on_epoch_end(state, epoch, loss, val_loss)
if state["stop"]:
break
return state
x = [row[0] for row in StandardScaler().fit_transform(X_houses)]
y = [price / 1000 for price in y_houses] # thousands of USD
x_tr, y_tr, x_val, y_val = x[:6], y[:6], x[6:], y[6:]
# TODO: BestOnValidation(patience) with best_loss, best_epoch and best_coefs
Hint 1

Keep four pieces of state: the best validation loss (start at math.inf), its epoch, the coefficients at that epoch, and a counter of epochs without improvement.

Hint 2

Save a copy of the coefficients when the loss improves: self.best_coefs = (state["coef"], state["intercept"]). When the counter reaches patience, write them back into state before you set the flag.

Solution
def fit_line(x_tr, y_tr, x_val, y_val, lr: float, epochs: int, callbacks: list) -> dict:
state = {"coef": 0.0, "intercept": 0.0, "stop": False, "epoch": 0}
n = len(x_tr)
def predict(a: float) -> float:
return state["intercept"] + state["coef"] * a
for epoch in range(1, epochs + 1):
err = [predict(a) - b for a, b in zip(x_tr, y_tr, strict=True)]
state["coef"] -= lr * 2 / n * sum(e * a for e, a in zip(err, x_tr, strict=True))
state["intercept"] -= lr * 2 / n * sum(err)
state["epoch"] = epoch
loss = sum(e * e for e in err) / n
val_err = [predict(a) - b for a, b in zip(x_val, y_val, strict=True)]
val_loss = sum(e * e for e in val_err) / len(val_err)
for cb in callbacks:
cb.on_epoch_end(state, epoch, loss, val_loss)
if state["stop"]:
break
return state
class BestOnValidation:
def __init__(self, patience: int) -> None:
self.patience = patience
self.best_loss = math.inf
self.best_epoch = 0
self.best_coefs = (0.0, 0.0)
self.waited = 0
def on_epoch_end(
self, state: dict, epoch: int, loss: float, val_loss: float
) -> None:
if val_loss < self.best_loss:
self.best_loss, self.best_epoch, self.waited = val_loss, epoch, 0
self.best_coefs = (state["coef"], state["intercept"])
else:
self.waited += 1
if self.waited >= self.patience:
state["coef"], state["intercept"] = self.best_coefs # restore
state["stop"] = True
x = [row[0] for row in StandardScaler().fit_transform(X_houses)]
y = [price / 1000 for price in y_houses] # thousands of USD
x_tr, y_tr, x_val, y_val = x[:6], y[:6], x[6:], y[6:]
best = BestOnValidation(patience=5)
state = fit_line(x_tr, y_tr, x_val, y_val, lr=0.05, epochs=300, callbacks=[best])
print(f"stopped at epoch {state['epoch']}, best epoch {best.best_epoch}")
print(f"best validation loss {best.best_loss:,.1f}; restored coef {state['coef']:.1f}")
assert state["epoch"] == best.best_epoch + 5
assert (state["coef"], state["intercept"]) == best.best_coefs
Output
stopped at epoch 27, best epoch 22
best validation loss 141.7; restored coef 154.9

How it works:

  1. The loop passes two losses. The callback ignores the training loss and watches only the validation loss, so the stopping rule changed without any edit to fit_line().
  2. The validation loss of the two held-out houses falls for about 20 epochs, then rises while the training loss still falls: the line starts to fit the six training houses at the cost of the other two.
  3. After five epochs without a new best, the callback restores the coefficients of the best epoch and stops the loop. The final state holds the best model, not the last one.
  4. The first assert proves the patience rule: training stops exactly five epochs after the best one.

Alternative: Keras’s EarlyStopping(monitor="val_loss", patience=5, restore_best_weights=True) implements this rule. Module 42 writes the same rule by hand in a PyTorch training loop. With two validation houses, the best epoch is noisy; real projects hold out more rows or use cross-validation (module 37).

M22-C10 · Predict the output: callbacks in a pipeline

Section titled “M22-C10 · Predict the output: callbacks in a pipeline”
Core

Predict the output: a small pipeline passes one Tracer callback to each of its steps. Read the code and write down every line it prints, in order. Then run it.

Acceptance criteria:

  • Write your prediction line by line before you run the code.
  • Your prediction matches the Output in the solution, in the same order.
Starter
class Tracer(Callback):
def __init__(self) -> None:
self.depth = 0
def on_fit_start(self, model: Any, X: Rows, y: list | None) -> None:
print(
" " * self.depth + f"start {type(model).__name__} ({len(X[0])} features)"
)
self.depth += 1
def on_fit_end(self, model: Any) -> None:
self.depth -= 1
print(" " * self.depth + f"end {type(model).__name__}")
tracer = Tracer()
steps = [StandardScaler(), StandardScaler(with_std=False), KNNClassifier(3)]
X = X_cust
for step in steps[:-1]:
X = step.fit(X, callbacks=[tracer]).transform(X)
steps[-1].fit(X, y_cust, callbacks=[tracer])
print(tracer.depth, round(X[0][0], 2))
Hint 1

fit() in the setup calls on_fit_start after validation and on_fit_end after _fit(). The steps are fitted one after the other, not inside each other.

Hint 2

Follow depth through each fit() call: when does it go up, and when does it come down again? For the last line, ask what the second scaler subtracts from data that the first scaler has already centered.

Solution
class Tracer(Callback):
def __init__(self) -> None:
self.depth = 0
def on_fit_start(self, model: Any, X: Rows, y: list | None) -> None:
print(
" " * self.depth + f"start {type(model).__name__} ({len(X[0])} features)"
)
self.depth += 1
def on_fit_end(self, model: Any) -> None:
self.depth -= 1
print(" " * self.depth + f"end {type(model).__name__}")
tracer = Tracer()
steps = [StandardScaler(), StandardScaler(with_std=False), KNNClassifier(3)]
X = X_cust
for step in steps[:-1]:
X = step.fit(X, callbacks=[tracer]).transform(X)
steps[-1].fit(X, y_cust, callbacks=[tracer])
print(tracer.depth, round(X[0][0], 2))
assert tracer.depth == 0
Output
start StandardScaler (2 features)
end StandardScaler
start StandardScaler (2 features)
end StandardScaler
start KNNClassifier (2 features)
end KNNClassifier
0 2.27

How it works:

  1. Each step’s fit() sends start, learns, then sends end. The next step starts only after the previous one ended, so depth goes 0 → 1 → 0 three times, and no line is indented.
  2. The y argument is missing for the scalers. That is fine, because TransformerMixin sets _requires_y = False.
  3. The first scaler gives the first customer a tenure of about 2.27 standard deviations above the mean. The second scaler subtracts the new mean, which is 0, so the value stays 2.27.
  4. One observer object served three different estimators. None of them knows what Tracer does.

Alternative: if one step fitted another step inside its own _fit() (a model that fits a scaler internally, for example), the events would nest, and the indentation would show it. The depth counter is there for that case.

M22-C11 · Build a pipeline from config with a builder

Section titled “M22-C11 · Build a pipeline from config with a builder”
Core

Write a Pipeline (steps as (name, step) pairs; fit() passes data through the transformers, predict() and score() use the last step) and a PipelineBuilder with add(name, step) (returns self; rejects duplicate names) and build() (rejects an empty pipeline and a non-transformer before the last step). Use the builder to build pipelines from the three config entries in the starter, with a small registry of model classes. Fit each on the first 15 customers, score it on the last 5, and print the result or the error.

Expected output
scaled knn accuracy 0.40
twice named ValueError: step 'scale' was already added
model first TypeError: step 'model' must be a transformer
Starter
REGISTRY = {
"scaler": StandardScaler,
"knn": KNNClassifier,
"majority": MajorityClassifier,
}
CONFIGS = {
"scaled knn": [["scale", "scaler", {}], ["model", "knn", {"n_neighbors": 1}]],
"twice named": [["scale", "scaler", {}], ["scale", "knn", {}]],
"model first": [["model", "knn", {}], ["scale", "scaler", {}]],
}
X_tr, y_tr, X_te, y_te = X_cust[:15], y_cust[:15], X_cust[15:], y_cust[15:]
# TODO: Pipeline, PipelineBuilder, build each config, fit, score, print
Hint 1

build() can check the order: every step but the last must have a transform attribute (hasattr).

Hint 2

Wrap the build-fit-score of one config in try/except (ValueError, TypeError), so that a bad config prints its error and the loop goes on.

Solution
class Pipeline:
def __init__(self, steps: list[tuple[str, Any]]) -> None:
self.steps = steps
def fit(self, X: Rows, y: list) -> Self:
for _, step in self.steps[:-1]:
X = step.fit_transform(X)
self.steps[-1][1].fit(X, y)
return self
def _transform(self, X: Rows) -> Rows:
for _, step in self.steps[:-1]:
X = step.transform(X)
return X
def predict(self, X: Rows) -> list:
return self.steps[-1][1].predict(self._transform(X))
def score(self, X: Rows, y: list) -> float:
return self.steps[-1][1].score(self._transform(X), y)
class PipelineBuilder:
def __init__(self) -> None:
self._steps: list[tuple[str, Any]] = []
def add(self, name: str, step: Any) -> Self:
if any(existing == name for existing, _ in self._steps):
raise ValueError(f"step {name!r} was already added")
self._steps.append((name, step))
return self
def build(self) -> Pipeline:
if not self._steps:
raise ValueError("a pipeline needs at least one step")
for name, step in self._steps[:-1]:
if not hasattr(step, "transform"):
raise TypeError(f"step {name!r} must be a transformer")
return Pipeline(list(self._steps))
REGISTRY = {
"scaler": StandardScaler,
"knn": KNNClassifier,
"majority": MajorityClassifier,
}
CONFIGS = {
"scaled knn": [["scale", "scaler", {}], ["model", "knn", {"n_neighbors": 1}]],
"twice named": [["scale", "scaler", {}], ["scale", "knn", {}]],
"model first": [["model", "knn", {}], ["scale", "scaler", {}]],
}
X_tr, y_tr, X_te, y_te = X_cust[:15], y_cust[:15], X_cust[15:], y_cust[15:]
results = {}
for label, entries in CONFIGS.items():
try:
builder = PipelineBuilder()
for name, kind, params in entries:
builder.add(name, REGISTRY[kind](**params))
pipe = builder.build().fit(X_tr, y_tr)
results[label] = pipe.score(X_te, y_te)
print(f"{label:<12} accuracy {results[label]:.2f}")
except (ValueError, TypeError) as err:
print(f"{label:<12} {type(err).__name__}: {err}")
assert list(results) == ["scaled knn"]
Output
scaled knn accuracy 0.40
twice named ValueError: step 'scale' was already added
model first TypeError: step 'model' must be a transformer

How it works:

  1. The builder checks each name as it arrives and the order at the end. The two broken configs fail with a message that names the step.
  2. Pipeline.fit() fits each transformer on the output of the previous one, and the model on the last output. score() sends the test rows through the same fitted transformers.
  3. The registry turns config names into classes, and the parameters into constructor arguments: factory, registry and builder together.
  4. A config error does not stop the loop: each experiment is independent.

Alternative: let Pipeline.__init__ run the same checks, as the lesson’s version does, so that a pipeline built without the builder is checked too. Then build() is a one-liner.

Core

A job lists the customers who signed up in the last 30 days. The starter version calls date.today(), so its output changes every day and cannot be tested. Rewrite it as new_customers(records, *, today=date.today, days=30), where today is a function that returns a date. Test it with a fake clock on the five records below, at two different dates, and print the ids found.

Expected output
2024-12-31: ['N0001', 'N0002', 'N0003', 'N0004', 'N0005']
2025-01-20: ['N0003', 'N0004', 'N0005']
last 7 days at 2024-12-31: ['N0004', 'N0005']
Starter
from datetime import date, timedelta
SIGNUPS = [
{"customer_id": "N0001", "signup_date": "2024-12-12"},
{"customer_id": "N0002", "signup_date": "2024-12-20"},
{"customer_id": "N0003", "signup_date": "2024-12-23"},
{"customer_id": "N0004", "signup_date": "2024-12-26"},
{"customer_id": "N0005", "signup_date": "2024-12-27"},
]
def new_customers_today(records):
cutoff = date.today() - timedelta(days=30)
return [
r["customer_id"]
for r in records
if date.fromisoformat(r["signup_date"]) > cutoff
]
# TODO: new_customers(records, *, today=date.today, days=30)
# TODO: call it with a fake clock for 2024-12-31 and for 2025-01-20
Hint 1

The parameter is the function date.today, not its result date.today(). Call it inside: cutoff = today() - timedelta(days=days).

Hint 2

A fake clock is lambda: date(2024, 12, 31).

Solution
from datetime import date, timedelta
SIGNUPS = [
{"customer_id": "N0001", "signup_date": "2024-12-12"},
{"customer_id": "N0002", "signup_date": "2024-12-20"},
{"customer_id": "N0003", "signup_date": "2024-12-23"},
{"customer_id": "N0004", "signup_date": "2024-12-26"},
{"customer_id": "N0005", "signup_date": "2024-12-27"},
]
def new_customers(
records: list[dict[str, str]],
*,
today: Callable[[], date] = date.today,
days: int = 30,
) -> list[str]:
cutoff = today() - timedelta(days=days)
return [
r["customer_id"]
for r in records
if date.fromisoformat(r["signup_date"]) > cutoff
]
at_year_end = new_customers(SIGNUPS, today=lambda: date(2024, 12, 31))
three_weeks_later = new_customers(SIGNUPS, today=lambda: date(2025, 1, 20))
print("2024-12-31:", at_year_end)
print("2025-01-20:", three_weeks_later)
print(
"last 7 days at 2024-12-31:",
new_customers(SIGNUPS, today=lambda: date(2024, 12, 31), days=7),
)
assert len(at_year_end) == 5
assert three_weeks_later == ["N0003", "N0004", "N0005"]
Output
2024-12-31: ['N0001', 'N0002', 'N0003', 'N0004', 'N0005']
2025-01-20: ['N0003', 'N0004', 'N0005']
last 7 days at 2024-12-31: ['N0004', 'N0005']

How it works:

  1. The default today=date.today keeps production calls short. It is a function, so the job reads the clock when it runs, not when it is defined.
  2. Each test passes a lambda that returns a fixed date. The result is the same on every day you run it.
  3. On 2025-01-20, the cutoff is 2024-12-21, so the signups of December 12 and 20 fall out.
  4. The days parameter makes the window a setting, so the 7-day check needs no new function.

Alternative: pass the date itself, as_of: date | None = None, and use as_of or date.today(). A value is simpler than a function when the job reads the clock only once.

M22-C13 · Choose a design for report formats

Section titled “M22-C13 · Choose a design for report formats”
Core

Choose a design and justify it: an analytics script exports churn rates as csv, json or markdown, chosen with a command-line flag. The team expects HTML next quarter. The three candidate designs are an if/elif chain, an abstract Formatter class with one subclass per format, and a dict of formatter functions with a registration decorator. Pick one, write two sentences of justification in a comment, and implement it for the rates below. Print each format.

Expected output
--- csv
contract,churn_rate
month-to-month,0.296
one-year,0.088
two-year,0.032
--- json
{"month-to-month": 0.296, "one-year": 0.088, "two-year": 0.032}
--- markdown
| contract | churn |
|---|---:|
| month-to-month | 29.6% |
| one-year | 8.8% |
| two-year | 3.2% |
Starter
rates = {"month-to-month": 0.296, "one-year": 0.088, "two-year": 0.032}
# Justification: TODO (two sentences)
# TODO: implement the chosen design and print the three formats
Hint 1

Ask: which design lets HTML be added without editing working code, and which one needs the least code per format?

Hint 2

A formatter has no settings and no state: it takes the rates and returns text. What does that suggest about classes?

Solution
import json
# Justification: a formatter takes the rates and returns text, with no settings or
# state, so a function per format is enough; a class hierarchy would add a base class
# and three classes for no gain. The registry dict lets next quarter's HTML format be
# added with one decorated function, without editing the dispatch code (open/closed).
FORMATTERS: dict[str, Callable[[dict[str, float]], str]] = {}
def formatter(name: str) -> Callable:
def decorator(func: Callable) -> Callable:
FORMATTERS[name] = func
return func
return decorator
@formatter("csv")
def to_csv(rates: dict[str, float]) -> str:
return "\n".join(["contract,churn_rate", *(f"{k},{v}" for k, v in rates.items())])
@formatter("json")
def to_json(rates: dict[str, float]) -> str:
return json.dumps(rates)
@formatter("markdown")
def to_markdown(rates: dict[str, float]) -> str:
rows = [f"| {k} | {v:.1%} |" for k, v in rates.items()]
return "\n".join(["| contract | churn |", "|---|---:|", *rows])
def export(rates: dict[str, float], fmt: str) -> str:
return FORMATTERS[fmt](rates)
rates = {"month-to-month": 0.296, "one-year": 0.088, "two-year": 0.032}
for fmt in sorted(FORMATTERS):
print(f"--- {fmt}")
print(export(rates, fmt))
assert sorted(FORMATTERS) == ["csv", "json", "markdown"]
assert json.loads(export(rates, "json")) == rates
Output
--- csv
contract,churn_rate
month-to-month,0.296
one-year,0.088
two-year,0.032
--- json
{"month-to-month": 0.296, "one-year": 0.088, "two-year": 0.032}
--- markdown
| contract | churn |
|---|---:|
| month-to-month | 29.6% |
| one-year | 8.8% |
| two-year | 3.2% |

How it works:

  1. The registry design meets both needs: a format is chosen by name from the command line, and a new format is a new function.
  2. The if/elif chain works for three formats, but HTML would edit it. The class hierarchy needs four classes for four functions, and every reader must open the base class to see that it adds nothing.
  3. sorted(FORMATTERS) also gives the valid choices for argparse: choices=sorted(FORMATTERS) (module 08).
  4. The JSON assert round-trips the output, which checks the format and the numbers in one line.

Alternative: the class design becomes right when formatters need settings or state, for example an ExcelFormatter(sheet_name=..., date_format=...) that keeps an open workbook. Until then, YAGNI.

M22-X01 · A self-documenting model registry

Section titled “M22-X01 · A self-documenting model registry”
Challenge

Write a registry for a team that wants to see which models exist and how to call them. register(name, *, aliases=()) stores the class under its name and each alias, and refuses any name that is taken. make_model(name, **params) builds a model; for an unknown name it suggests the closest known names with difflib.get_close_matches. describe_models() returns one line per class (not per alias): the name, the aliases, the default parameters from get_params() and the first line of the docstring. Register KNNClassifier (alias neighbors), LinearRegression (alias ols) and MajorityClassifier, and show every feature.

Expected output
knn (neighbors): {'n_neighbors': 5, 'distance': Distance.EUCLIDEAN}
Majority vote of the k nearest training rows.
linear (ols): {'fit_intercept': True}
Least-squares line through one feature.
majority: {}
Baseline: the most common training label.
KNNClassifier(n_neighbors=3, distance=Distance.EUCLIDEAN)
unknown model 'knm'; did you mean 'knn'?
name 'ols' is already used by LinearRegression
Starter
import difflib
MODELS: dict[str, type] = {}
ALIASES: dict[type, list[str]] = {}
# TODO: register(name, *, aliases=()), make_model(name, **params), describe_models()
# TODO: register three models, print describe_models(), build by alias, try "knm" and a duplicate
Hint 1

Keep the primary names separately (for example in ALIASES, keyed by class) so that describe_models() lists each class once.

Hint 2

cls().get_params() gives the defaults, because every minilearn constructor has defaults. (cls.__doc__ or "").strip().splitlines()[0] gives the first docstring line; give the classes a docstring if they have none.

Hint 3

difflib.get_close_matches("knm", sorted(MODELS), n=2) returns the closest names.

Solution
import difflib
MODELS: dict[str, type] = {}
ALIASES: dict[type, list[str]] = {}
def register(name: str, *, aliases: Sequence[str] = ()) -> Callable[[type], type]:
def decorator(cls: type) -> type:
for key in (name, *aliases):
if key in MODELS:
raise ValueError(
f"name {key!r} is already used by {MODELS[key].__name__}"
)
for key in (name, *aliases):
MODELS[key] = cls
ALIASES[cls] = [name, *aliases]
return cls
return decorator
def make_model(name: str, **params: Any) -> Any:
if name not in MODELS:
close = difflib.get_close_matches(name, sorted(MODELS), n=2)
hint = f"; did you mean {' or '.join(map(repr, close))}?" if close else ""
raise ValueError(f"unknown model {name!r}{hint}")
return MODELS[name](**params)
def describe_models() -> str:
lines = []
for cls, names in sorted(ALIASES.items(), key=lambda item: item[1][0]):
doc = (cls.__doc__ or "").strip().splitlines()[0]
alias_text = f" ({', '.join(names[1:])})" if names[1:] else ""
lines.append(f"{names[0]}{alias_text}: {cls().get_params()}\n {doc}")
return "\n".join(lines)
KNNClassifier.__doc__ = "Majority vote of the k nearest training rows."
LinearRegression.__doc__ = "Least-squares line through one feature."
MajorityClassifier.__doc__ = "Baseline: the most common training label."
register("knn", aliases=["neighbors"])(KNNClassifier)
register("linear", aliases=["ols"])(LinearRegression)
register("majority")(MajorityClassifier)
print(describe_models())
print(make_model("neighbors", n_neighbors=3))
for bad in (lambda: make_model("knm"), lambda: register("ols")(MeanRegressor)):
try:
bad()
except ValueError as err:
print(err)
assert make_model("ols") == make_model("linear")
assert len(MODELS) == 5 and len(ALIASES) == 3
Output
knn (neighbors): {'n_neighbors': 5, 'distance': Distance.EUCLIDEAN}
Majority vote of the k nearest training rows.
linear (ols): {'fit_intercept': True}
Least-squares line through one feature.
majority: {}
Baseline: the most common training label.
KNNClassifier(n_neighbors=3, distance=Distance.EUCLIDEAN)
unknown model 'knm'; did you mean 'knn'?
name 'ols' is already used by LinearRegression

How it works:

  1. register() checks every name before it stores any of them, so a failed registration leaves the registry unchanged.
  2. ALIASES maps each class to its names. describe_models() loops over it, so each class appears once, sorted by its primary name.
  3. The defaults come from get_params() on a fresh object: the documentation can never drift from the code.
  4. difflib.get_close_matches() ranks the known names by similarity. “knm” is close to “knn”, so the error suggests it. Tools such as git (“did you mean…?”) and pip do the same.

Alternative: store a small dataclass per entry (name, cls, aliases, summary) instead of two dicts. That is cleaner once entries get more fields, such as a version or a “deprecated” flag.

M22-X02 · A grid search from factory, strategy and observer

Section titled “M22-X02 · A grid search from factory, strategy and observer”
Challenge

Write grid_search(make, grid, X_tr, y_tr, X_val, y_val, *, callbacks=()). make is a factory that returns a fresh model, and grid maps parameter names to lists of values. For every combination (use itertools.product), it sets the parameters with set_params(), fits, scores and notifies each callback with on_candidate(params, score). It returns the best (params, score); ties go to the first candidate. Write a Leaderboard callback that keeps the top 3 candidates and a CountCandidates callback. Search n_neighbors in [1, 3, 5] and distance in ["euclidean", "manhattan"] for KNN on the scaled customers; rows 1, 5, 9, 13 and 17 are the validation set.

Expected output
6 candidates; best {'n_neighbors': 3, 'distance': 'euclidean'} accuracy 0.80
candidate 2: {'n_neighbors': 3, 'distance': 'euclidean'} 0.80
candidate 3: {'n_neighbors': 3, 'distance': 'manhattan'} 0.80
candidate 4: {'n_neighbors': 5, 'distance': 'euclidean'} 0.80
Starter
import itertools
is_val = [i % 4 == 1 for i in range(len(X_cust))] # rows 1, 5, 9, 13 and 17
X_tr = [row for row, t in zip(X_cust, is_val, strict=True) if not t]
X_val = [row for row, t in zip(X_cust, is_val, strict=True) if t]
y_tr = [v for v, t in zip(y_cust, is_val, strict=True) if not t]
y_val = [v for v, t in zip(y_cust, is_val, strict=True) if t]
scaler = StandardScaler().fit(X_tr)
X_tr, X_val = scaler.transform(X_tr), scaler.transform(X_val)
grid = {"n_neighbors": [1, 3, 5], "distance": ["euclidean", "manhattan"]}
# TODO: grid_search(...), Leaderboard(top=3), CountCandidates
Hint 1

itertools.product(*grid.values()) gives tuples of values. dict(zip(grid, values, strict=True)) turns each tuple into a parameter dict.

Hint 2

Keep the best with a strict > comparison, so that a later candidate with the same score does not replace the first one.

Hint 3

Leaderboard can count the candidates it has seen, append (score, index, params) and keep sorted(...)[: top] with the key (-score, index). Do not use len(self.rows) as the index: the list is cut to the top 3.

Solution
import itertools
def grid_search(
make: Callable[[], Any],
grid: dict[str, list[Any]],
X_tr: Rows,
y_tr: list,
X_val: Rows,
y_val: list,
*,
callbacks: Sequence[Any] = (),
) -> tuple[dict[str, Any], float]:
best: tuple[dict[str, Any], float] = ({}, -math.inf)
for values in itertools.product(*grid.values()):
params = dict(zip(grid, values, strict=True))
model = make().set_params(**params)
score = model.fit(X_tr, y_tr).score(X_val, y_val)
for cb in callbacks:
cb.on_candidate(params, score)
if score > best[1]:
best = (params, score)
return best
class Leaderboard:
def __init__(self, top: int = 3) -> None:
self.top = top
self.seen = 0 # candidates so far: the index of the next one
self.rows: list[tuple[float, int, dict[str, Any]]] = []
def on_candidate(self, params: dict[str, Any], score: float) -> None:
self.rows.append((score, self.seen, params))
self.seen += 1
self.rows = sorted(self.rows, key=lambda r: (-r[0], r[1]))[: self.top]
class CountCandidates:
def __init__(self) -> None:
self.count = 0
def on_candidate(self, params: dict[str, Any], score: float) -> None:
self.count += 1
is_val = [i % 4 == 1 for i in range(len(X_cust))] # rows 1, 5, 9, 13 and 17
X_tr = [row for row, t in zip(X_cust, is_val, strict=True) if not t]
X_val = [row for row, t in zip(X_cust, is_val, strict=True) if t]
y_tr = [v for v, t in zip(y_cust, is_val, strict=True) if not t]
y_val = [v for v, t in zip(y_cust, is_val, strict=True) if t]
scaler = StandardScaler().fit(X_tr)
X_tr, X_val = scaler.transform(X_tr), scaler.transform(X_val)
grid = {"n_neighbors": [1, 3, 5], "distance": ["euclidean", "manhattan"]}
board, counter = Leaderboard(top=3), CountCandidates()
best_params, best_score = grid_search(
KNNClassifier, grid, X_tr, y_tr, X_val, y_val, callbacks=[board, counter]
)
print(f"{counter.count} candidates; best {best_params} accuracy {best_score:.2f}")
for score, index, params in board.rows:
print(f" candidate {index}: {params} {score:.2f}")
assert counter.count == 6 and len(board.rows) == 3 and board.seen == 6
assert [index for _, index, _ in board.rows] == [2, 3, 4]
assert best_score == board.rows[0][0]
Output
6 candidates; best {'n_neighbors': 3, 'distance': 'euclidean'} accuracy 0.80
candidate 2: {'n_neighbors': 3, 'distance': 'euclidean'} 0.80
candidate 3: {'n_neighbors': 3, 'distance': 'manhattan'} 0.80
candidate 4: {'n_neighbors': 5, 'distance': 'euclidean'} 0.80

How it works:

  1. make is a factory: the class KNNClassifier itself works, because calling it returns a fresh model. set_params() returns self, so the parameters and the factory chain in one line.

  2. The distance names are strategies: the grid searches over algorithms and numbers alike.

  3. The search loop is the subject. It does not know how many observers there are or what they keep. Leaderboard and CountCandidates were written without touching grid_search().

  4. On five validation rows, accuracy moves in steps of 0.2, so ties are common. The candidate number in the leaderboard (0 to 5, in grid order) shows which candidate came first.

  5. The best score is optimistic: the search picked the candidate that happened to do best on these five rows. Report the chosen model’s quality only after a final check on untouched test rows, or use cross-validation (module 37).

Alternative: scikit-learn’s GridSearchCV(KNeighborsClassifier(), param_grid=grid, cv=5) does the same with cross-validation, and stores all results in cv_results_ instead of calling observers (module 37).

M22-X03 · Refactor a procedural churn script

Section titled “M22-X03 · Refactor a procedural churn script”
Challenge

Refactor: the script in the starter reads data/customers.csv, computes the churn rate per plan for customers with at most 12 months of tenure, and prints a report, all at module level. Rewrite it as small functions: load_records(path), filter_new(records, max_tenure), churn_by(records, column), format_report(rates, title), and run(*, read, log, max_tenure=12) that wires them with injected I/O. Check that run() prints the same lines as the original on the real file, then test run() with a fake reader of four records and a list logger.

Expected output
Churn of customers with tenure <= 12 months (1967 customers)
basic 30.8% (253 of 822)
premium 49.5% (180 of 364)
standard 28.6% (223 of 781)
Churn of customers with tenure <= 12 months (3 customers)
Starter
with open("data/customers.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
new = [r for r in rows if int(r["tenure_months"]) <= 12]
stats = {}
for r in new:
c, n = stats.get(r["plan"], (0, 0))
stats[r["plan"]] = (c + int(r["churned"]), n + 1)
print(f"Churn of customers with tenure <= 12 months ({len(new)} customers)")
for plan in sorted(stats):
c, n = stats[plan]
print(f" {plan:<10}{c / n:6.1%} ({c} of {n})")
# TODO: rewrite as functions with an injected reader and logger
Hint 1

Capture the original output first: put the original code in a function that takes log and call it with original.append. Then compare it with your new run(log=new.append).

Hint 2

format_report() returns a list of lines; run() sends each line to log. Then a test can check each line.

Hint 3

The fake reader ignores its path argument: read=lambda path: fake_records.

Solution
def original_script(log: Callable[[str], None]) -> None:
with open("data/customers.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
new = [r for r in rows if int(r["tenure_months"]) <= 12]
stats: dict[str, tuple[int, int]] = {}
for r in new:
c, n = stats.get(r["plan"], (0, 0))
stats[r["plan"]] = (c + int(r["churned"]), n + 1)
log(f"Churn of customers with tenure <= 12 months ({len(new)} customers)")
for plan in sorted(stats):
c, n = stats[plan]
log(f" {plan:<10}{c / n:6.1%} ({c} of {n})")
type Records = list[dict[str, str]]
def load_records(path: str) -> Records:
with open(path, encoding="utf-8", newline="") as f:
return list(csv.DictReader(f))
def filter_new(records: Records, max_tenure: int) -> Records:
return [r for r in records if int(r["tenure_months"]) <= max_tenure]
def churn_by(records: Records, column: str) -> dict[str, tuple[int, int]]:
groups: dict[str, list[int]] = {}
for rec in records:
groups.setdefault(rec[column], []).append(int(rec["churned"]))
return {k: (sum(v), len(v)) for k, v in sorted(groups.items())}
def format_report(rates: dict[str, tuple[int, int]], title: str) -> list[str]:
return [
title,
*(f" {k:<10}{c / n:6.1%} ({c} of {n})" for k, (c, n) in rates.items()),
]
def run(
path: str = "data/customers.csv",
*,
read: Callable[[str], Records] = load_records,
log: Callable[[str], None] = print,
max_tenure: int = 12,
) -> dict[str, tuple[int, int]]:
new = filter_new(read(path), max_tenure)
rates = churn_by(new, "plan")
title = (
f"Churn of customers with tenure <= {max_tenure} months ({len(new)} customers)"
)
for line in format_report(rates, title):
log(line)
return rates
before: list[str] = []
after: list[str] = []
original_script(before.append)
run(log=after.append)
print("\n".join(after))
assert after == before
fake = [
{"plan": "basic", "tenure_months": "3", "churned": "1"},
{"plan": "basic", "tenure_months": "5", "churned": "0"},
{"plan": "premium", "tenure_months": "2", "churned": "1"},
{"plan": "premium", "tenure_months": "40", "churned": "1"},
]
lines: list[str] = []
rates = run("fake.csv", read=lambda path: fake, log=lines.append)
print(lines[0])
assert rates == {"basic": (1, 2), "premium": (1, 1)}
Output
Churn of customers with tenure <= 12 months (1967 customers)
basic 30.8% (253 of 822)
premium 49.5% (180 of 364)
standard 28.6% (223 of 781)
Churn of customers with tenure <= 12 months (3 customers)

How it works:

  1. The first assert is a characterization test: it records what the old code does and proves that the new code does the same, before anyone changes the behavior.
  2. Each function has one job and can be tested alone. filter_new() and churn_by() need no file at all.
  3. run() is the only function with side effects, and both of them (reading and logging) are injected with production defaults.
  4. The fake test checks the filter (the 40-month customer is excluded) and the computation, in microseconds.
  5. Interpretation: among new customers, premium plans churn the most, which matches the course data’s pattern of high charges driving churn.

Alternative: max_tenure could become a strategy, keep: Callable[[dict], bool], so that the same job reports any segment. Do that when a second segment is actually needed.

M22-X04 · Remove over-engineering without changing behavior

Section titled “M22-X04 · Remove over-engineering without changing behavior”
Challenge

Refactor: the starter formats revenue figures for a report with an abstract strategy, two strategy classes, a singleton factory and a context object with a getter and a setter. Replace all of it with at most two small functions and a dict, and keep the exact same output for every format and value. A "compact" format turns 1,234,567 into 1.2M, and a "full" format into 1,234,567.00 USD.

Expected output
full ['458.94 USD', '12,400.00 USD', '1,234,567.00 USD', '2,500,000,000.00 USD']
compact ['459', '12.4K', '1.2M', '2.5B']
same output: True
Starter
class MoneyFormatStrategy(ABC):
@abstractmethod
def format(self, amount: float) -> str: ...
class FullFormat(MoneyFormatStrategy):
def format(self, amount: float) -> str:
return f"{amount:,.2f} USD"
class CompactFormat(MoneyFormatStrategy):
def format(self, amount: float) -> str:
for limit, suffix in ((1e9, "B"), (1e6, "M"), (1e3, "K")):
if abs(amount) >= limit:
return f"{amount / limit:.1f}{suffix}"
return f"{amount:.0f}"
class FormatFactory:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def create(self, kind: str) -> MoneyFormatStrategy:
if kind == "full":
return FullFormat()
if kind == "compact":
return CompactFormat()
raise ValueError(kind)
class MoneyFormatter:
def __init__(self, kind: str) -> None:
self._strategy = FormatFactory().create(kind)
def get_strategy(self) -> MoneyFormatStrategy:
return self._strategy
def set_strategy(self, strategy: MoneyFormatStrategy) -> None:
self._strategy = strategy
def format(self, amount: float) -> str:
return self.get_strategy().format(amount)
values = [458.94, 12_400.0, 1_234_567.0, 2_500_000_000.0]
for kind in ("full", "compact"):
print(kind, [MoneyFormatter(kind).format(v) for v in values])
# TODO: replace the classes with functions and a dict
Hint 1

Run the starter and save its output in a list first, so that you can assert that the new code prints the same.

Hint 2

Each strategy class becomes a function. The factory becomes a dict. The context object becomes one function format_money(amount, kind).

Solution
class MoneyFormatStrategy(ABC):
@abstractmethod
def format(self, amount: float) -> str: ...
class FullFormat(MoneyFormatStrategy):
def format(self, amount: float) -> str:
return f"{amount:,.2f} USD"
class CompactFormat(MoneyFormatStrategy):
def format(self, amount: float) -> str:
for limit, suffix in ((1e9, "B"), (1e6, "M"), (1e3, "K")):
if abs(amount) >= limit:
return f"{amount / limit:.1f}{suffix}"
return f"{amount:.0f}"
class FormatFactory:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def create(self, kind: str) -> MoneyFormatStrategy:
if kind == "full":
return FullFormat()
if kind == "compact":
return CompactFormat()
raise ValueError(kind)
class MoneyFormatter:
def __init__(self, kind: str) -> None:
self._strategy = FormatFactory().create(kind)
def get_strategy(self) -> MoneyFormatStrategy:
return self._strategy
def set_strategy(self, strategy: MoneyFormatStrategy) -> None:
self._strategy = strategy
def format(self, amount: float) -> str:
return self.get_strategy().format(amount)
values = [458.94, 12_400.0, 1_234_567.0, 2_500_000_000.0]
old = {
kind: [MoneyFormatter(kind).format(v) for v in values]
for kind in ("full", "compact")
}
# --- after: two functions and a dict ------------------------------------------
def compact(amount: float) -> str:
for limit, suffix in ((1e9, "B"), (1e6, "M"), (1e3, "K")):
if abs(amount) >= limit:
return f"{amount / limit:.1f}{suffix}"
return f"{amount:.0f}"
MONEY_FORMATS: dict[str, Callable[[float], str]] = {
"full": lambda amount: f"{amount:,.2f} USD",
"compact": compact,
}
new = {kind: [MONEY_FORMATS[kind](v) for v in values] for kind in MONEY_FORMATS}
for kind, texts in new.items():
print(kind, texts)
print("same output:", new == old)
assert new == old
Output
full ['458.94 USD', '12,400.00 USD', '1,234,567.00 USD', '2,500,000,000.00 USD']
compact ['459', '12.4K', '1.2M', '2.5B']
same output: True

How it works:

  1. The characterization step stores the old output in old before anything changes. The final assert proves that the refactoring kept the behavior exactly.
  2. The abstract base had two subclasses, but each subclass was one function, so the dict of functions keeps the strategy idea with no classes.
  3. The singleton factory guarded nothing: it had no state. A dict lookup does its job. The getter and setter around _strategy added nothing over a plain attribute, and no caller used the setter (YAGNI).
  4. Five classes, about 45 lines, became one function and a dict, about 10 lines. A new format is still one function and one dict entry: the open/closed benefit survives the simplification.

Alternative: if a format needs settings, such as the currency, turn the lambda into def full(amount, currency="USD") and use functools.partial(full, currency="EUR"), or a closure. Reach for a class only when a format keeps state between calls.

M22-X05 · An event bus for a data-cleaning pipeline

Section titled “M22-X05 · An event bus for a data-cleaning pipeline”
Challenge

Write an EventBus with subscribe(event, handler) and publish(event, **data), which calls every handler of that event with the keyword arguments, in subscription order. Then write clean_orders(rows, bus): it keeps an order when its quantity is between 1 and 50 and its revenue equals quantity × unit price × (1 − discount) within 0.01, and publishes "row_rejected" (with the order id and a reason) or "row_kept", and at the end "done" (with the counts). Subscribe three independent handlers: a counter of rejection reasons, a printer of rejected ids, and a summary line. The orders are typed in the starter.

Expected output
rejected O000002: quantity
rejected O000004: revenue
rejected O000005: quantity
done: 2 kept, 3 rejected
reasons: {'quantity': 2, 'revenue': 1}
kept ids: ['O000001', 'O000003']
Starter
ORDERS = [
{
"order_id": "O000001",
"quantity": 2,
"unit_price": 79.99,
"discount": 0.0,
"revenue": 159.98,
},
{
"order_id": "O000002",
"quantity": 0,
"unit_price": 249.0,
"discount": 0.0,
"revenue": 0.0,
},
{
"order_id": "O000003",
"quantity": 3,
"unit_price": 129.95,
"discount": 0.1,
"revenue": 350.87,
},
{
"order_id": "O000004",
"quantity": 1,
"unit_price": 49.5,
"discount": 0.2,
"revenue": 49.5,
},
{
"order_id": "O000005",
"quantity": 75,
"unit_price": 12.0,
"discount": 0.0,
"revenue": 900.0,
},
]
# TODO: EventBus, clean_orders(rows, bus), and three handlers
Hint 1

Store handlers in a defaultdict(list) keyed by event name. publish() loops over self._handlers[event] and calls handler(**data).

Hint 2

Each handler accepts **data or exactly the keywords of its event, for example def print_rejected(order_id, reason): ....

Hint 3

Use math.isclose(expected, revenue, abs_tol=0.01) for the revenue check.

Solution
from collections import defaultdict
class EventBus:
def __init__(self) -> None:
self._handlers: dict[str, list[Callable[..., None]]] = defaultdict(list)
def subscribe(self, event: str, handler: Callable[..., None]) -> None:
self._handlers[event].append(handler)
def publish(self, event: str, **data: Any) -> None:
for handler in self._handlers[event]:
handler(**data)
def clean_orders(rows: list[dict[str, Any]], bus: EventBus) -> list[dict[str, Any]]:
kept = []
for row in rows:
expected = row["quantity"] * row["unit_price"] * (1 - row["discount"])
if not 1 <= row["quantity"] <= 50:
bus.publish("row_rejected", order_id=row["order_id"], reason="quantity")
elif not math.isclose(expected, row["revenue"], abs_tol=0.01):
bus.publish("row_rejected", order_id=row["order_id"], reason="revenue")
else:
kept.append(row)
bus.publish("row_kept", order_id=row["order_id"])
bus.publish("done", kept=len(kept), rejected=len(rows) - len(kept))
return kept
ORDERS = [
{
"order_id": "O000001",
"quantity": 2,
"unit_price": 79.99,
"discount": 0.0,
"revenue": 159.98,
},
{
"order_id": "O000002",
"quantity": 0,
"unit_price": 249.0,
"discount": 0.0,
"revenue": 0.0,
},
{
"order_id": "O000003",
"quantity": 3,
"unit_price": 129.95,
"discount": 0.1,
"revenue": 350.87,
},
{
"order_id": "O000004",
"quantity": 1,
"unit_price": 49.5,
"discount": 0.2,
"revenue": 49.5,
},
{
"order_id": "O000005",
"quantity": 75,
"unit_price": 12.0,
"discount": 0.0,
"revenue": 900.0,
},
]
reasons: Counter[str] = Counter()
bus = EventBus()
bus.subscribe("row_rejected", lambda order_id, reason: reasons.update([reason]))
bus.subscribe(
"row_rejected", lambda order_id, reason: print(f"rejected {order_id}: {reason}")
)
bus.subscribe(
"done", lambda kept, rejected: print(f"done: {kept} kept, {rejected} rejected")
)
kept = clean_orders(ORDERS, bus)
print("reasons:", dict(sorted(reasons.items())))
print("kept ids:", [row["order_id"] for row in kept])
assert reasons == {"quantity": 2, "revenue": 1}
Output
rejected O000002: quantity
rejected O000004: revenue
rejected O000005: quantity
done: 2 kept, 3 rejected
reasons: {'quantity': 2, 'revenue': 1}
kept ids: ['O000001', 'O000003']

How it works:

  1. clean_orders() is the subject. It publishes what happened and never decides what to do about it. Nobody subscribed to "row_kept", and that is fine: publishing to no handler does nothing.
  2. Each handler is a lambda with the exact keywords of its event. The counter and the printer listen to the same event independently.
  3. Order O000003: 3 × 129.95 × 0.9 = 350.865, which is within 0.01 of 350.87, so it is kept. Order O000004 has a 20% discount, but its revenue ignores it.
  4. This is the design of Django signals and of browser events: the code that sends an event does not import the code that reacts to it, so both sides stay decoupled.

Alternative: with only one listener, pass a function: clean_orders(rows, on_reject=print). A bus pays off when several unrelated parts of a program react to the same events.

M22-X06 · End to end: churn experiments from a config

Section titled “M22-X06 · End to end: churn experiments from a config”
Challenge

Combine the patterns on the real customer file. Write a factory registry for "scaler", "knn" and "majority"; a FitLogger(log) callback; and run(config, *, read, log), which loads data/customers.csv (every 10th customer: 500 rows) with the features tenure_months, logins_last_30d and support_tickets, uses rows whose position is a multiple of 4 as the validation set, and, for each experiment in the config, builds the steps by name, fits them with the callback, and logs the accuracy. The experiments are given in the starter. Run it with print as the logger.

Expected output
375 train rows, 125 validation rows
baseline
fit MajorityClassifier on 375 rows
accuracy 0.808
knn15
fit StandardScaler on 375 rows
fit KNNClassifier on 375 rows
accuracy 0.816
knn15 manhattan
fit StandardScaler on 375 rows
fit KNNClassifier on 375 rows
accuracy 0.848
Starter
CONFIG = {
"features": ["tenure_months", "logins_last_30d", "support_tickets"],
"every": 10,
"experiments": {
"baseline": [["majority", {}]],
"knn15": [["scaler", {}], ["knn", {"n_neighbors": 15}]],
"knn15 manhattan": [
["scaler", {}],
["knn", {"n_neighbors": 15, "distance": "manhattan"}],
],
},
}
# TODO: MODELS and make_model, FitLogger(log), run(config, *, read, log)
Hint 1

Load the records once with the injected read("data/customers.csv"), take records[:: config["every"]], and split by position with i % 4 == 0.

Hint 2

For one experiment, fit the transformers in order with fit_transform(X, callbacks=...), keep each fitted step, and fit the last step with y. Transform the validation rows with the same fitted steps.

Hint 3

FitLogger.on_fit_start can log f" fit {name} on {len(X)} rows". Pass callbacks=[FitLogger(log)] to every fit().

Solution
MODELS: dict[str, type] = {
"scaler": StandardScaler,
"knn": KNNClassifier,
"majority": MajorityClassifier,
}
def make_model(name: str, **params: Any) -> Any:
return MODELS[name](**params)
class FitLogger(Callback):
def __init__(self, log: Callable[[str], None] = print) -> None:
self.log = log
def on_fit_start(self, model: Any, X: Rows, y: list | None) -> None:
self.log(f" fit {type(model).__name__} on {len(X)} rows")
def read_csv_records(path: str) -> list[dict[str, str]]:
with open(path, encoding="utf-8", newline="") as f:
return list(csv.DictReader(f))
def run(
config: dict[str, Any],
*,
read: Callable[[str], list[dict[str, str]]] = read_csv_records,
log: Callable[[str], None] = print,
) -> dict[str, float]:
records = read("data/customers.csv")[:: config["every"]]
X = [[float(r[name]) for name in config["features"]] for r in records]
y = [int(r["churned"]) for r in records]
is_val = [i % 4 == 0 for i in range(len(X))] # the validation rows
X_tr = [row for row, t in zip(X, is_val, strict=True) if not t]
X_val = [row for row, t in zip(X, is_val, strict=True) if t]
y_tr = [v for v, t in zip(y, is_val, strict=True) if not t]
y_val = [v for v, t in zip(y, is_val, strict=True) if t]
log(f"{len(X_tr)} train rows, {len(X_val)} validation rows")
callbacks = [FitLogger(log)]
scores = {}
for label, steps in config["experiments"].items():
log(label)
models = [make_model(name, **params) for name, params in steps]
Xt_tr, Xt_val = X_tr, X_val
for step in models[:-1]:
Xt_tr = step.fit_transform(Xt_tr, callbacks=callbacks)
Xt_val = step.transform(Xt_val)
models[-1].fit(Xt_tr, y_tr, callbacks=callbacks)
scores[label] = models[-1].score(Xt_val, y_val)
log(f" accuracy {scores[label]:.3f}")
return scores
CONFIG = {
"features": ["tenure_months", "logins_last_30d", "support_tickets"],
"every": 10,
"experiments": {
"baseline": [["majority", {}]],
"knn15": [["scaler", {}], ["knn", {"n_neighbors": 15}]],
"knn15 manhattan": [
["scaler", {}],
["knn", {"n_neighbors": 15, "distance": "manhattan"}],
],
},
}
scores = run(CONFIG)
assert set(scores) == {"baseline", "knn15", "knn15 manhattan"}
fake = [
{
"tenure_months": "5",
"logins_last_30d": "2",
"support_tickets": "1",
"churned": str(i % 2),
}
for i in range(80)
]
quiet: list[str] = []
run(CONFIG, read=lambda path: fake, log=quiet.append)
assert quiet[0] == "6 train rows, 2 validation rows"
Output
375 train rows, 125 validation rows
baseline
fit MajorityClassifier on 375 rows
accuracy 0.808
knn15
fit StandardScaler on 375 rows
fit KNNClassifier on 375 rows
accuracy 0.816
knn15 manhattan
fit StandardScaler on 375 rows
fit KNNClassifier on 375 rows
accuracy 0.848

How it works:

  1. The config is plain data: names, numbers and lists. It could be a JSON file, and adding an experiment needs no code.
  2. make_model() turns names into fresh estimators, and the registry decides which names exist. KNN gets its distance strategy from the config too.
  3. Every fit() goes through the template in the setup, so FitLogger reports every step without any code in the estimators. The logger is injected, so the second call collects the lines silently.
  4. The fake reader proves the wiring (80 records, every 10th → 8 rows, 2 validation rows) without the 5,000-row file.
  5. Interpretation: with the support tickets added, KNN with the Manhattan distance reaches 0.848 on the validation rows, against the baseline’s 0.808, and the Euclidean version 0.816. To know whether the tickets caused the gain, rerun the config without them: that is one edit to the features list. These are validation scores of a comparison, so the best one is optimistic: refit the chosen experiment and score it once on untouched test rows, or use cross-validation (module 37), before you report it.

Alternative: the mini-project wraps the steps in a Pipeline built by a PipelineBuilder, and uses train_test_split with a shuffle. The loop over models here is that pipeline written inline.