Skip to content

20. The Python data model — Exercises

These exercises practice every idea of the Python data model lesson. You give classes a repr, make them comparable, sortable and hashable, turn them into containers and callables, and overload operators. The data comes from the course files: data/sales.csv, data/sensors.csv, data/customers.csv, data/houses.csv, data/reviews.csv and others.

How to work:

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

Each solution ends with assert checks. Add the same checks to your own code.

Every exercise on this page starts with these imports. Paste the block at the top of each script.

import csv
import inspect
import math
import re
import statistics
import unicodedata
from collections import Counter
from collections.abc import Callable, Iterable, Iterator
from functools import total_ordering
from itertools import islice, product
from typing import Any, Self
Warm-up

The plant’s monitoring script prints sensor objects in logs and in reports. Write a class Sensor with the attributes sensor_id and location. Its repr must look like the constructor call, Sensor('S1', 'server room'). Its str is for the report: S1 (server room). Print the sensor, its repr, and a list that holds it.

Expected output
S1 (server room)
Sensor('S1', 'server room')
[Sensor('S1', 'server room')]
Starter
class Sensor:
def __init__(self, sensor_id: str, location: str) -> None:
self.sensor_id = sensor_id
self.location = location
# TODO: __repr__ returns "Sensor('S1', 'server room')"
# TODO: __str__ returns "S1 (server room)"
sensor = Sensor("S1", "server room")
# TODO: print the sensor, its repr and [sensor]
Hint 1

print(x) uses __str__. repr(x) and the items of a list use __repr__.

Hint 2

Inside __repr__, write {self.sensor_id!r}: the !r flag adds the quotes for you.

Solution
class Sensor:
def __init__(self, sensor_id: str, location: str) -> None:
self.sensor_id = sensor_id
self.location = location
def __repr__(self) -> str:
return f"Sensor({self.sensor_id!r}, {self.location!r})"
def __str__(self) -> str:
return f"{self.sensor_id} ({self.location})"
sensor = Sensor("S1", "server room")
print(sensor)
print(repr(sensor))
print([sensor])
assert repr(sensor) == "Sensor('S1', 'server room')"
assert str(sensor) == "S1 (server room)"
assert eval(repr(sensor)).location == "server room" # the repr rebuilds the object
Output
S1 (server room)
Sensor('S1', 'server room')
[Sensor('S1', 'server room')]

How it works:

  1. print(sensor) calls str(sensor), which runs __str__.
  2. repr(sensor) runs __repr__. The !r flag calls repr() on each string, which adds the quotes.
  3. A list shows the repr of each item, never the str.
  4. The last assert proves that the repr is valid code: eval() builds an equal sensor from it.

Alternative: writing the quotes by hand, f"Sensor('{self.sensor_id}', ...)", looks the same for simple values but breaks for a location such as O'Hare hangar: the repr then has three quotes and is no longer valid code. !r escapes it correctly.

M20-W02 · Predict the output of str, repr and the conversion flags

Section titled “M20-W02 · Predict the output of str, repr and the conversion flags”
Warm-up

Predict the output: read the code and write down, line by line, what it prints. Then run it.

Starter
class Product:
def __init__(self, product_id: str, price: float) -> None:
self.product_id = product_id
self.price = price
def __repr__(self) -> str:
return f"Product({self.product_id!r}, {self.price!r})"
def __str__(self) -> str:
return f"{self.product_id} at {self.price:.2f} USD"
p = Product("P002", 249.0)
print(p)
print(f"{p!r}")
print([p])
print(f"{p=}")
print({"best seller": p})
print(str(p) == format(p))

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.
Hint 1

Containers (lists, dicts) always show the repr of what they hold.

Hint 2

{p=} prints the expression text, an equals sign and the repr. format(p) with no spec gives the same text as str(p).

Solution
class Product:
def __init__(self, product_id: str, price: float) -> None:
self.product_id = product_id
self.price = price
def __repr__(self) -> str:
return f"Product({self.product_id!r}, {self.price!r})"
def __str__(self) -> str:
return f"{self.product_id} at {self.price:.2f} USD"
p = Product("P002", 249.0)
print(p)
print(f"{p!r}")
print([p])
print(f"{p=}")
print({"best seller": p})
print(str(p) == format(p))
assert f"{p}" == "P002 at 249.00 USD"
assert f"{p!r}" == repr(p)
Output
P002 at 249.00 USD
Product('P002', 249.0)
[Product('P002', 249.0)]
p=Product('P002', 249.0)
{'best seller': Product('P002', 249.0)}
True

How it works:

  1. print(p) uses __str__: the price shows with 2 decimals.
  2. !r forces the repr. Inside the repr, {self.price!r} shows 249.0, the plain float repr, not the formatted price.
  3. A list and a dict show the repr of each value.
  4. {p=} is the debugging form: it shows p= and the repr.
  5. format(p) with no spec calls object.__format__, which returns str(p).
Warm-up

A loader groups order ids into batches. Write a class Batch that stores a list of order ids. len(batch) must give the number of ids. An empty batch must be falsy, so the loader can write if not batch:. Do not write __bool__.

Expected output
5
False
nothing to process
Starter
class Batch:
def __init__(self, order_ids: list[str]) -> None:
self.order_ids = order_ids
# TODO: __len__
batch = Batch(["O000001", "O000002", "O000003", "O000004", "O000005"])
empty = Batch([])
# TODO: print len(batch) and bool(empty)
# TODO: if not empty: print "nothing to process"
Hint 1

__len__ must return an int. Return the length of the list.

Hint 2

Without __bool__, Python uses __len__ for truth: 0 means falsy.

Solution
class Batch:
def __init__(self, order_ids: list[str]) -> None:
self.order_ids = order_ids
def __len__(self) -> int:
return len(self.order_ids)
batch = Batch(["O000001", "O000002", "O000003", "O000004", "O000005"])
empty = Batch([])
print(len(batch))
print(bool(empty))
if not empty:
print("nothing to process")
assert len(batch) == 5 and len(empty) == 0
assert batch and not empty
Output
5
False
nothing to process

How it works:

  1. len(batch) runs Batch.__len__, which returns the length of the list.
  2. bool(empty) finds no __bool__, so it calls __len__. The result 0 makes the batch falsy.
  3. if not empty: uses the same rule, so the message prints.

Alternative: write __bool__ too, return bool(self.order_ids). It gives the same result. Write it only when truth should mean something other than “not empty”.

Warm-up

Fix the bug: the code should count the distinct stores in five sales lines from data/sales.csv. It crashes with TypeError: unhashable type: 'StoreKey'. Make StoreKey hashable, consistently with its __eq__.

Expected output
5 lines, 4 stores
StoreKey('S04', 'South')
StoreKey('S05', 'South')
StoreKey('S10', 'West')
StoreKey('S11', 'West')
Starter
class StoreKey:
def __init__(self, store_id: str, region: str) -> None:
self.store_id = store_id
self.region = region
def __repr__(self) -> str:
return f"StoreKey({self.store_id!r}, {self.region!r})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, StoreKey):
return NotImplemented
return (self.store_id, self.region) == (other.store_id, other.region)
# TODO: the fix goes here
lines = [
StoreKey("S11", "West"),
StoreKey("S10", "West"),
StoreKey("S05", "South"),
StoreKey("S11", "West"),
StoreKey("S04", "South"),
]
unique = set(lines)
print(len(lines), "lines,", len(unique), "stores")
for key in sorted(unique, key=lambda k: k.store_id):
print(key)
Hint 1

Look at StoreKey.__hash__ before the fix. What does a class with __eq__ and no __hash__ get?

Hint 2

Hash the same fields that __eq__ compares, as one tuple.

Solution
class StoreKey:
def __init__(self, store_id: str, region: str) -> None:
self.store_id = store_id
self.region = region
def __repr__(self) -> str:
return f"StoreKey({self.store_id!r}, {self.region!r})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, StoreKey):
return NotImplemented
return (self.store_id, self.region) == (other.store_id, other.region)
def __hash__(self) -> int:
return hash((self.store_id, self.region))
lines = [
StoreKey("S11", "West"),
StoreKey("S10", "West"),
StoreKey("S05", "South"),
StoreKey("S11", "West"),
StoreKey("S04", "South"),
]
unique = set(lines)
print(len(lines), "lines,", len(unique), "stores")
for key in sorted(unique, key=lambda k: k.store_id):
print(key)
assert len(unique) == 4
assert hash(StoreKey("S11", "West")) == hash(lines[0])
Output
5 lines, 4 stores
StoreKey('S04', 'South')
StoreKey('S05', 'South')
StoreKey('S10', 'West')
StoreKey('S11', 'West')

How it works:

  1. Defining __eq__ without __hash__ set StoreKey.__hash__ to None, so set() refused the objects.
  2. The new __hash__ hashes the tuple of the same two fields that __eq__ compares. Equal keys now have equal hashes, as the hash contract requires.
  3. The set keeps one S11 key, so 5 lines give 4 stores. sorted() with a key prints them in a fixed order, because a set has no order of its own.

Alternative: if you do not need value equality, delete __eq__. The default identity-based __eq__ and __hash__ then apply, but two StoreKey("S11", "West") objects count as two stores, which is wrong here.

Warm-up

The data dictionary says that every age in data/customers.csv lies between 18 and 80. Write a class ValidRange with __contains__, so that age in valid checks the range (both ends included) and is False for anything that is not a number. Then list the invalid values of a hand-typed batch of ages.

Expected output
ValidRange(18, 80)
[17, 81, '45', None]
Starter
class ValidRange:
def __init__(self, low: float, high: float) -> None:
self.low = low
self.high = high
# TODO: __repr__ and __contains__
valid = ValidRange(18, 80)
ages = [34, 17, 52, 81, 18, 80, "45", None]
# TODO: print valid, then the values that are not in valid
Hint 1

__contains__(self, value) returns a bool. A chained comparison checks both ends: self.low <= value <= self.high.

Hint 2

Test the type first with isinstance(value, int | float). "45" <= 80 would raise a TypeError otherwise.

Solution
class ValidRange:
def __init__(self, low: float, high: float) -> None:
self.low = low
self.high = high
def __repr__(self) -> str:
return f"ValidRange({self.low!r}, {self.high!r})"
def __contains__(self, value: object) -> bool:
return isinstance(value, int | float) and self.low <= value <= self.high
valid = ValidRange(18, 80)
ages = [34, 17, 52, 81, 18, 80, "45", None]
print(valid)
print([age for age in ages if age not in valid])
assert 18 in valid and 80 in valid and 17 not in valid
assert "45" not in valid
Output
ValidRange(18, 80)
[17, 81, '45', None]

How it works:

  1. age in valid calls valid.__contains__(age). not in calls the same method and inverts the result.
  2. isinstance() rejects the string "45" and None before any comparison runs. and stops early, so the comparison never sees them.
  3. The chained comparison includes both ends, so 18 and 80 are valid.

Alternative: range(18, 81) also supports in, but only for whole numbers: 18.5 in range(18, 81) is False. ValidRange works for floats too.

Warm-up

Write a class LinearUnit that converts a value with value * scale + offset. Its objects must be callable, so you can pass one to map(). Convert three Celsius readings from data/readings.txt (lines 37 to 39) to Fahrenheit, rounded to 2 decimals.

Expected output
LinearUnit(1.8, 32)
[67.1, 69.26, 68.18]
Starter
class LinearUnit:
def __init__(self, scale: float, offset: float = 0.0) -> None:
self.scale = scale
self.offset = offset
# TODO: __repr__ and __call__
to_fahrenheit = LinearUnit(9 / 5, 32)
celsius = [19.5, 20.7, 20.1]
# TODO: print the converter and the converted readings
Hint 1

__call__(self, value) runs when you write to_fahrenheit(value).

Hint 2

map(to_fahrenheit, celsius) calls the object once per reading. Round in a list comprehension: [round(f, 2) for f in map(...)].

Solution
class LinearUnit:
def __init__(self, scale: float, offset: float = 0.0) -> None:
self.scale = scale
self.offset = offset
def __repr__(self) -> str:
return f"LinearUnit({self.scale!r}, {self.offset!r})"
def __call__(self, value: float) -> float:
return value * self.scale + self.offset
to_fahrenheit = LinearUnit(9 / 5, 32)
celsius = [19.5, 20.7, 20.1]
print(to_fahrenheit)
print([round(f, 2) for f in map(to_fahrenheit, celsius)])
assert math.isclose(to_fahrenheit(100), 212)
assert callable(to_fahrenheit)
Output
LinearUnit(1.8, 32)
[67.1, 69.26, 68.18]

How it works:

  1. to_fahrenheit(value) runs LinearUnit.__call__. The object keeps its two settings in attributes.
  2. map() accepts any callable, so the object works where a function is expected.
  3. The repr shows the settings, which a lambda cannot do.

Alternative: a closure (module 05): def linear_unit(scale, offset): return lambda v: v * scale + offset. It is shorter, but its repr is <function linear_unit.<locals>.<lambda> at 0x...>, and you cannot read its settings back.

M20-W07 · Predict who handles the operator

Section titled “M20-W07 · Predict who handles the operator”
Warm-up

Predict the output: write down, line by line, what the code prints. Each special method prints its own name when Python calls it.

Starter
class Left:
def __add__(self, other: object) -> object:
print("Left.__add__")
return NotImplemented
class Right:
def __radd__(self, other: object) -> object:
print("Right.__radd__")
return "handled by Right"
print(Left() + Right())
print(1 + Right())
try:
print(Right() + 1)
except TypeError as error:
print("TypeError:", error)

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.
Hint 1

For a + b, Python calls a.__add__(b) first. Only when it is missing or returns NotImplemented does Python call b.__radd__(a).

Hint 2

In Right() + 1, the left operand is a Right. Does Right have __add__? Does int have __radd__ that knows Right?

Solution
class Left:
def __add__(self, other: object) -> object:
print("Left.__add__")
return NotImplemented
class Right:
def __radd__(self, other: object) -> object:
print("Right.__radd__")
return "handled by Right"
print(Left() + Right())
print(1 + Right())
try:
print(Right() + 1)
except TypeError as error:
print("TypeError:", error)
assert 1 + Right() == "handled by Right"
Output
Left.__add__
Right.__radd__
handled by Right
Right.__radd__
handled by Right
TypeError: unsupported operand type(s) for +: 'Right' and 'int'
Right.__radd__

How it works:

  1. Left() + Right(): Left.__add__ runs and returns NotImplemented, so Python tries Right.__radd__, which handles it.
  2. 1 + Right(): int.__add__ does not know Right and returns NotImplemented. Python tries Right.__radd__. This is the path that sum() takes.
  3. Right() + 1: Right has no __add__, and int.__radd__ does not know Right. Both sides decline, so Python raises TypeError.
  4. The assert line calls __radd__ once more, so Right.__radd__ is the last printed line.

M20-W08 · Make a zero discount falsy with bool

Section titled “M20-W08 · Make a zero discount falsy with bool”
Warm-up

The discount column of data/sales.csv holds 0.0, 0.05, 0.1 or 0.2. Write a class Discount whose objects are falsy when the rate is 0, like the number 0. Use it to keep only the discounted lines of the first sales lines below.

Expected output
[Discount(0.05), Discount(0.1)]
2 of 6 lines discounted
Starter
class Discount:
def __init__(self, rate: float) -> None:
self.rate = rate
# TODO: __repr__ and __bool__
discounts = [Discount(r) for r in (0.05, 0.0, 0.0, 0.0, 0.1, 0.0)]
# TODO: keep the truthy discounts and print them
# TODO: print "2 of 6 lines discounted"
Hint 1

__bool__ must return a real bool, not a float.

Hint 2

[d for d in discounts if d] keeps the truthy ones, because if d calls bool(d).

Solution
class Discount:
def __init__(self, rate: float) -> None:
self.rate = rate
def __repr__(self) -> str:
return f"Discount({self.rate!r})"
def __bool__(self) -> bool:
return self.rate != 0
discounts = [Discount(r) for r in (0.05, 0.0, 0.0, 0.0, 0.1, 0.0)]
discounted = [d for d in discounts if d]
print(discounted)
print(f"{len(discounted)} of {len(discounts)} lines discounted")
assert not Discount(0.0) and Discount(0.2)
assert len(discounted) == 2
Output
[Discount(0.05), Discount(0.1)]
2 of 6 lines discounted

How it works:

  1. if d calls bool(d), which runs Discount.__bool__.
  2. self.rate != 0 is a comparison, so it returns a real bool. Returning self.rate itself would raise TypeError: __bool__ should return bool, returned float.
  3. The six rates are the discounts of the first six lines of the file.

Alternative: return bool(self.rate) gives the same result, because 0.0 is falsy.

M20-C01 · Sort model versions with total_ordering

Section titled “M20-C01 · Sort model versions with total_ordering”
Core

A model registry stores versions such as "1.10.0". The deploy script must pick the newest one. Sorting the strings gives the wrong order, because "1.10.0" < "1.9.3" compares character by character. Write a class ModelVersion with @total_ordering, __eq__, __hash__ and __lt__ that compares the parts as numbers. Print the string sort, the version sort and the newest version.

Expected output
['1.10.0', '1.10.1', '1.2.0', '1.4.0', '1.9.3', '2.0.0']
['1.2.0', '1.4.0', '1.9.3', '1.10.0', '1.10.1', '2.0.0']
ModelVersion('2.0.0') True
Starter
@total_ordering
class ModelVersion:
def __init__(self, text: str) -> None:
self.parts = tuple(int(p) for p in text.split("."))
def __str__(self) -> str:
return ".".join(str(p) for p in self.parts)
# TODO: __repr__, __eq__, __hash__ and __lt__
versions = ["1.2.0", "1.10.0", "1.9.3", "2.0.0", "1.10.1", "1.4.0"]
# TODO: print sorted(versions)
# TODO: print the versions sorted as ModelVersion objects (as strings)
# TODO: print the newest version and ModelVersion("1.10.0") >= ModelVersion("1.9.3")
Hint 1

Tuples compare element by element, as numbers when the elements are numbers: (1, 10, 0) > (1, 9, 3).

Hint 2

@total_ordering needs __eq__ and one ordering method. It writes __le__, __gt__ and __ge__ for you. Return NotImplemented for other types.

Solution
@total_ordering
class ModelVersion:
def __init__(self, text: str) -> None:
self.parts = tuple(int(p) for p in text.split("."))
def __str__(self) -> str:
return ".".join(str(p) for p in self.parts)
def __repr__(self) -> str:
return f"ModelVersion({str(self)!r})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, ModelVersion):
return NotImplemented
return self.parts == other.parts
def __hash__(self) -> int:
return hash(self.parts)
def __lt__(self, other: object) -> bool:
if not isinstance(other, ModelVersion):
return NotImplemented
return self.parts < other.parts
versions = ["1.2.0", "1.10.0", "1.9.3", "2.0.0", "1.10.1", "1.4.0"]
print(sorted(versions))
ordered = sorted(ModelVersion(v) for v in versions)
print([str(v) for v in ordered])
newest = max(ModelVersion(v) for v in versions)
print(repr(newest), ModelVersion("1.10.0") >= ModelVersion("1.9.3"))
assert ordered[-1] == ModelVersion("2.0.0")
assert ModelVersion("1.10.0") > ModelVersion("1.9.3")
assert len({ModelVersion("1.4.0"), ModelVersion("1.4.0")}) == 1
Output
['1.10.0', '1.10.1', '1.2.0', '1.4.0', '1.9.3', '2.0.0']
['1.2.0', '1.4.0', '1.9.3', '1.10.0', '1.10.1', '2.0.0']
ModelVersion('2.0.0') True

How it works:

  1. __init__ splits "1.10.0" into the tuple (1, 10, 0) of integers.
  2. __lt__ compares the tuples. Tuples compare their first elements, then the second ones, and so on, so (1, 10, 0) > (1, 9, 3).
  3. @total_ordering builds >= from __lt__ and __eq__. sorted() and max() need only <.
  4. A version never changes after creation, so __hash__ from the same tuple is safe. Equal versions collapse in a set.

Alternative: without a class, sort with a key: sorted(versions, key=lambda v: tuple(map(int, v.split(".")))). That is enough for a one-off script. The class wins when versions are compared in many places, because the rule lives in one spot.

M20-C02 · Add up revenue exactly with sum()

Section titled “M20-C02 · Add up revenue exactly with sum()”
Core

Add the revenue of the first 10 lines of data/sales.csv in two ways: as floats, and as Money objects that store whole cents. Write Money with __repr__, __str__, __eq__, __add__ and __radd__, so that sum() works on a list of Money. Print both totals.

Expected output
floats: 2856.1099999999997
money: 2,856.11 USD Money(285611)
Starter
class Money:
def __init__(self, cents: int) -> None:
self.cents = cents
@classmethod
def from_text(cls, text: str) -> Self:
return cls(round(float(text) * 100))
# TODO: __repr__ -> Money(6649), __str__ -> 66.49 USD
# TODO: __eq__, __add__, __radd__
with open("data/sales.csv", encoding="utf-8", newline="") as f:
rows = list(islice(csv.DictReader(f), 10))
# TODO: print the float sum and the Money sum
Hint 1

sum() starts from 0 and computes 0 + first. That calls int.__add__, which returns NotImplemented, and then Money.__radd__(first, 0).

Hint 2

In __radd__, return self when other == 0. Otherwise return NotImplemented.

Solution
class Money:
def __init__(self, cents: int) -> None:
self.cents = cents
@classmethod
def from_text(cls, text: str) -> Self:
return cls(round(float(text) * 100))
def __repr__(self) -> str:
return f"Money({self.cents})"
def __str__(self) -> str:
return f"{self.cents / 100:,.2f} USD"
def __eq__(self, other: object) -> bool:
if not isinstance(other, Money):
return NotImplemented
return self.cents == other.cents
def __add__(self, other: object) -> "Money":
if not isinstance(other, Money):
return NotImplemented
return Money(self.cents + other.cents)
def __radd__(self, other: object) -> "Money":
if other == 0:
return self
return NotImplemented
with open("data/sales.csv", encoding="utf-8", newline="") as f:
rows = list(islice(csv.DictReader(f), 10))
float_total = sum(float(row["revenue"]) for row in rows)
money_total = sum(Money.from_text(row["revenue"]) for row in rows)
print("floats:", float_total)
print("money: ", money_total, repr(money_total))
assert money_total == Money(285611)
assert math.isclose(float_total, money_total.cents / 100)
Output
floats: 2856.1099999999997
money: 2,856.11 USD Money(285611)

How it works:

  1. Money.from_text turns "66.49" into 6,649 cents once. round() removes the tiny float error of 66.49 * 100.
  2. sum() computes 0 + m1. int declines, and Money.__radd__ returns m1. After that, every step is Money + Money, which __add__ handles.
  3. The float sum shows 2856.1099999999997 because each float is approximate. The integer cents sum is exact.

Alternative: skip __radd__ and give sum() a start value: sum(items, start=Money(0)). That works, but every caller must remember it. __radd__ makes plain sum(items) work.

Core

Fix the bug: this Units class should add the quantity of the first 12 lines of data/sales.csv. sum(units) never finishes normally. It raises RecursionError: maximum recursion depth exceeded. Find the cause and fix __radd__.

Expected output
Units(14)
Starter
class Units:
def __init__(self, n: int) -> None:
self.n = n
def __repr__(self) -> str:
return f"Units({self.n})"
def __add__(self, other: object) -> "Units":
if not isinstance(other, Units):
return NotImplemented
return Units(self.n + other.n)
def __radd__(self, other: object) -> "Units":
return other + self # "the same as __add__, the other way round"
with open("data/sales.csv", encoding="utf-8", newline="") as f:
units = [Units(int(row["quantity"])) for row in islice(csv.DictReader(f), 12)]
print(sum(units))
Hint 1

Follow sum(): it computes 0 + units[0]. Which method runs? What does that method compute?

Hint 2

other + self with other = 0 is again 0 + units[0]: Python asks Units.__radd__ again, which asks again, without end.

Solution
class Units:
def __init__(self, n: int) -> None:
self.n = n
def __repr__(self) -> str:
return f"Units({self.n})"
def __add__(self, other: object) -> "Units":
if not isinstance(other, Units):
return NotImplemented
return Units(self.n + other.n)
def __radd__(self, other: object) -> "Units":
if other == 0: # the start value of sum()
return self
return NotImplemented
with open("data/sales.csv", encoding="utf-8", newline="") as f:
units = [Units(int(row["quantity"])) for row in islice(csv.DictReader(f), 12)]
total = sum(units)
print(total)
assert total.n == 14
Output
Units(14)

How it works:

  1. sum() evaluates 0 + units[0]. int.__add__ returns NotImplemented, so Python calls units[0].__radd__(0).
  2. The old __radd__ evaluated 0 + self: the very same expression. Python called __radd__ again, and again, until the call stack limit raised RecursionError.
  3. The fixed __radd__ handles the one case it needs, the start value 0, and declines everything else.

Alternative: when addition is the same in both directions, a reflected method can call the normal one: return self.__add__(other). Here that would decline the 0, so the 0 case still needs its own line.

M20-C04 · A table you can index three ways

Section titled “M20-C04 · A table you can index three ways”
Core

Load data/stores.csv into a class Table that stores one list per column. Like a DataFrame, it must answer three kinds of key: a column name gives the column, an integer gives one row as a dict, and a slice gives a smaller Table. Add __len__ and a short __repr__. Print the table, the first and last rows, the cities of a slice and the total floor area.

Expected output
Table(12 rows, columns=['store_id', 'city', 'region', 'size_sqm', 'opened'])
{'store_id': 'S12', 'city': 'Denver', 'region': 'West', 'size_sqm': '1350', 'opened': '2023-06-15'}
Chicago ['Houston', 'Atlanta', 'Miami']
total floor area: 26,230 m²
Starter
class Table:
def __init__(self, columns: dict[str, list[Any]]) -> None:
self.columns = columns
@classmethod
def from_csv(cls, path: str) -> Self:
with open(path, encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
return cls({name: [row[name] for row in rows] for name in rows[0]})
# TODO: __repr__ -> Table(12 rows, columns=['store_id', ...])
# TODO: __len__
# TODO: __getitem__ for str, int and slice keys
stores = Table.from_csv("data/stores.csv")
# TODO: print stores, stores[-1], stores[0]["city"], stores[3:6]["city"]
# TODO: print the total of size_sqm
Hint 1

Test the key type with isinstance(key, str), isinstance(key, int) and isinstance(key, slice). Raise TypeError for anything else.

Hint 2

For an integer, build {name: values[key] for name, values in self.columns.items()}. For a slice, apply the same slice to every column and wrap the result in type(self)(...).

Solution
class Table:
def __init__(self, columns: dict[str, list[Any]]) -> None:
self.columns = columns
@classmethod
def from_csv(cls, path: str) -> Self:
with open(path, encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
return cls({name: [row[name] for row in rows] for name in rows[0]})
def __repr__(self) -> str:
return f"Table({len(self)} rows, columns={list(self.columns)!r})"
def __len__(self) -> int:
return len(next(iter(self.columns.values()), []))
def __getitem__(self, key: str | int | slice) -> Any:
if isinstance(key, str):
return self.columns[key] # KeyError for an unknown column
if isinstance(key, int):
return {name: values[key] for name, values in self.columns.items()}
if isinstance(key, slice):
return type(self)({n: v[key] for n, v in self.columns.items()})
kind = type(key).__name__
raise TypeError(f"Table keys must be str, int or slice, not {kind}")
stores = Table.from_csv("data/stores.csv")
print(stores)
print(stores[-1])
print(stores[0]["city"], stores[3:6]["city"])
print(f"total floor area: {sum(int(s) for s in stores['size_sqm']):,} m²")
assert len(stores) == 12 and len(stores[3:6]) == 3
assert stores["store_id"][0] == stores[0]["store_id"] == "S01"
Output
Table(12 rows, columns=['store_id', 'city', 'region', 'size_sqm', 'opened'])
{'store_id': 'S12', 'city': 'Denver', 'region': 'West', 'size_sqm': '1350', 'opened': '2023-06-15'}
Chicago ['Houston', 'Atlanta', 'Miami']
total floor area: 26,230 m²

How it works:

  1. stores["city"] is a str key, so __getitem__ returns that column list.
  2. stores[-1] and stores[0] are int keys. The method picks the same position in every column and returns a dict. Negative positions work because lists understand them.
  3. stores[3:6] passes a slice object. Slicing every column keeps the rows aligned, and type(self)(...) returns a Table, so ["city"] works on the result.
  4. __len__ measures the first column. next(iter(...), []) handles a table with no columns.

Alternative: store a list of row dicts instead of a dict of columns. Row access becomes trivial and column access needs a loop. A column store, like pandas and Polars use, makes column work fast, which is what analysis does most.

M20-C05 · Refactor vector functions into operators

Section titled “M20-C05 · Refactor vector functions into operators”
Core

Refactor procedural code into a class. The script below compares a new house listing with three sold houses from data/houses.csv. Each house is a feature vector: thousands of square feet, bedrooms and bathrooms. It measures the distance to each sold house and the midpoint of two houses with five helper functions. Rewrite it with a Vector class that supports +, -, * (with the number on either side), @ and abs(). The output must stay the same.

Expected output
H0001 1.906
H0003 1.136
H0004 0.5
[1.84, 3.0, 2.75] 16.24
Starter
def vec_add(a, b):
return [x + y for x, y in zip(a, b)]
def vec_sub(a, b):
return [x - y for x, y in zip(a, b)]
def vec_scale(a, k):
return [x * k for x in a]
def vec_dot(a, b):
return sum(x * y for x, y in zip(a, b))
def vec_norm(a):
return math.sqrt(vec_dot(a, a))
listing = [1.8, 3, 2.0]
sold = {"H0001": [2.42, 4, 3.5], "H0003": [1.26, 2, 2.0], "H0004": [1.79, 3, 2.5]}
for house_id, features in sold.items():
print(house_id, round(vec_norm(vec_sub(features, listing)), 3))
midpoint = vec_scale(vec_add(sold["H0001"], sold["H0003"]), 0.5)
print([round(x, 3) for x in midpoint], round(vec_dot(listing, listing), 2))
# TODO: rewrite with a Vector class and operators
Hint 1

Map each function to a method: vec_add → __add__, vec_sub → __sub__, vec_scale → __mul__ and __rmul__, vec_dot → __matmul__, vec_norm → __abs__.

Hint 2

Make __iter__ return iter(self.values). Then zip(self, other), round(x, 3) for x in v and list(v) all work.

Solution
class Vector:
def __init__(self, values: Iterable[float]) -> None:
self.values = tuple(values)
def __repr__(self) -> str:
return f"Vector({list(self.values)!r})"
def __iter__(self) -> Iterator[float]:
return iter(self.values)
def __add__(self, other: object) -> "Vector":
if not isinstance(other, Vector):
return NotImplemented
return Vector(x + y for x, y in zip(self, other, strict=True))
def __sub__(self, other: object) -> "Vector":
if not isinstance(other, Vector):
return NotImplemented
return Vector(x - y for x, y in zip(self, other, strict=True))
def __mul__(self, k: object) -> "Vector":
if not isinstance(k, int | float):
return NotImplemented
return Vector(x * k for x in self)
__rmul__ = __mul__
def __matmul__(self, other: object) -> float:
if not isinstance(other, Vector):
return NotImplemented
return sum(x * y for x, y in zip(self, other, strict=True))
def __abs__(self) -> float:
return math.sqrt(self @ self)
listing = Vector([1.8, 3, 2.0])
sold = {
"H0001": Vector([2.42, 4, 3.5]),
"H0003": Vector([1.26, 2, 2.0]),
"H0004": Vector([1.79, 3, 2.5]),
}
for house_id, features in sold.items():
print(house_id, round(abs(features - listing), 3))
midpoint = 0.5 * (sold["H0001"] + sold["H0003"])
print([round(x, 3) for x in midpoint], round(listing @ listing, 2))
closest = min(sold, key=lambda h: abs(sold[h] - listing))
assert closest == "H0004"
assert math.isclose(abs(Vector([3, 4])), 5)
Output
H0001 1.906
H0003 1.136
H0004 0.5
[1.84, 3.0, 2.75] 16.24

How it works:

  1. Each helper function became a special method. The call sites now read like the math: abs(features - listing) is ∥f−l∥\lVert f - l \rVert, the distance.
  2. 0.5 * (a + b) needs __rmul__, because the float is on the left. __rmul__ = __mul__ reuses the method.
  3. zip(..., strict=True) raises ValueError for vectors of different lengths, which the old helpers silently cut short.
  4. House H0004 (1,790 sqft, 3 bedrooms, 2.5 baths) is closest to the listing in this feature space. A real model would scale the features first, because one bedroom counts as much as 1,000 square feet here.

Alternative: NumPy arrays (module 23) already have all these operators, and they are much faster: np.linalg.norm(a - b). Writing the class once shows what NumPy does for you.

Core

Write a class SensorSeries that streams one sensor’s temperature_c values from data/sensors.csv. Its __iter__ must read the file again on every loop, so that max(), sum() and a second loop all see every value. It must skip blank cells. Add __repr__ and __len__. Print the series, the count, the mean and the maximum for sensor S3.

Expected output
SensorSeries('data/sensors.csv', 'S3', column='temperature_c')
2010 23.53 41.66
Starter
class SensorSeries:
def __init__(
self, path: str, sensor_id: str, column: str = "temperature_c"
) -> None:
self.path = path
self.sensor_id = sensor_id
self.column = column
# TODO: __repr__
# TODO: __iter__: a generator that opens the file and yields floats
# TODO: __len__: count the values (one pass over the file)
s3 = SensorSeries("data/sensors.csv", "S3")
# TODO: print s3, len(s3), the mean (2 decimals) and max(s3)
Hint 1

Put yield inside __iter__. Each call of iter(s3) then creates a fresh generator that opens the file again.

Hint 2

__len__ can count with sum(1 for _ in self). It must return an int.

Solution
class SensorSeries:
def __init__(
self, path: str, sensor_id: str, column: str = "temperature_c"
) -> None:
self.path = path
self.sensor_id = sensor_id
self.column = column
def __repr__(self) -> str:
args = f"{self.path!r}, {self.sensor_id!r}, column={self.column!r}"
return f"SensorSeries({args})"
def __iter__(self) -> Iterator[float]:
with open(self.path, encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["sensor_id"] == self.sensor_id and row[self.column]:
yield float(row[self.column])
def __len__(self) -> int:
return sum(1 for _ in self)
s3 = SensorSeries("data/sensors.csv", "S3")
print(s3)
n = len(s3)
print(n, f"{sum(s3) / n:.2f}", max(s3))
assert n == sum(1 for _ in s3) # a second full pass sees every value again
assert 0 < n <= 2016
Output
SensorSeries('data/sensors.csv', 'S3', column='temperature_c')
2010 23.53 41.66

How it works:

  1. __iter__ is a generator method. Every for, sum() or max() calls iter(s3), which starts a new generator that opens the file from the top.
  2. The generator filters the rows of S3 and skips blank cells, then converts each value to float.
  3. __len__ counts with one full pass. It is correct but costs a file read, so the code stores the result in n instead of calling len() twice.
  4. The object never holds the data, only the path and the names, so it uses almost no memory.

Alternative: read the values once into a list in __init__. Every later operation is then fast, but the class holds all the data. Choose the streaming form for files that do not fit in memory (module 10).

M20-C07 · Interpret the reading that vanished from a set

Section titled “M20-C07 · Interpret the reading that vanished from a set”
Core

Interpret a result: a gateway keeps the readings it already processed in a set. After a drift correction, the set says that it no longer contains the reading, although the reading is still inside it:

class Reading:
def __init__(self, sensor_id: str, celsius: float) -> None:
self.sensor_id = sensor_id
self.celsius = celsius
def __eq__(self, other: object) -> bool:
if not isinstance(other, Reading):
return NotImplemented
return (self.sensor_id, self.celsius) == (other.sensor_id, other.celsius)
def __hash__(self) -> int:
return hash((self.sensor_id, self.celsius))
r = Reading("S3", 22.9)
seen = {r}
r.celsius = round(r.celsius - 0.35, 2) # correct one day of drift
print(r in seen)
print(len(seen), any(x is r for x in seen))
Output
False
1 True

Explain both output lines. Then fix the design so that this bug cannot happen: make Reading immutable and give it a method corrected(delta) that returns a new reading. After the fix, the script in the solution prints:

Expected output
True False
1 Reading('S3', 22.55)
AttributeError: property 'celsius' of 'Reading' object has no setter
Starter
class Reading:
def __init__(self, sensor_id: str, celsius: float) -> None:
self.sensor_id = sensor_id
self.celsius = celsius
def __eq__(self, other: object) -> bool:
if not isinstance(other, Reading):
return NotImplemented
return (self.sensor_id, self.celsius) == (other.sensor_id, other.celsius)
def __hash__(self) -> int:
return hash((self.sensor_id, self.celsius))
r = Reading("S3", 22.9)
seen = {r}
r.celsius = round(r.celsius - 0.35, 2) # correct one day of drift
print(r in seen)
print(len(seen), any(x is r for x in seen))
# TODO: explain the output, then make Reading immutable
Hint 1

A set stores each object in a bucket chosen by its hash at insertion time. What happens to the hash of r when celsius changes?

Hint 2

Make the fields read-only with @property (module 18) and add a method that returns a corrected new reading.

Solution
class Reading:
"""An immutable reading: fields are read-only properties."""
def __init__(self, sensor_id: str, celsius: float) -> None:
self._sensor_id = sensor_id
self._celsius = celsius
@property
def sensor_id(self) -> str:
return self._sensor_id
@property
def celsius(self) -> float:
return self._celsius
def corrected(self, delta: float) -> "Reading":
return Reading(self.sensor_id, round(self.celsius + delta, 2))
def __repr__(self) -> str:
return f"Reading({self.sensor_id!r}, {self.celsius!r})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, Reading):
return NotImplemented
return (self.sensor_id, self.celsius) == (other.sensor_id, other.celsius)
def __hash__(self) -> int:
return hash((self.sensor_id, self.celsius))
r = Reading("S3", 22.9)
seen = {r}
fixed = r.corrected(-0.35)
print(r in seen, fixed in seen)
print(len(seen), fixed)
try:
r.celsius = 22.55
except AttributeError as error:
print("AttributeError:", error)
assert r in seen and fixed not in seen
Output
True False
1 Reading('S3', 22.55)
AttributeError: property 'celsius' of 'Reading' object has no setter

How it works:

  1. In the original code, seen = {r} put r in the bucket for hash(("S3", 22.9)).
  2. The correction changed celsius to 22.55, so hash(r) changed too. r in seen looked in the bucket for ("S3", 22.55), found nothing and printed False.
  3. The set still holds the object: len(seen) is 1, and any(x is r ...) finds it by identity. The object sits in a bucket that no lookup reaches any more.
  4. The fix makes the fields read-only properties with no setter, so assignment raises AttributeError. A correction creates a new reading, and the old one keeps its hash.

Alternative: module 21’s @dataclass(frozen=True) writes this immutable class, its __eq__ and its __hash__ for you in three lines.

M20-C08 · Override settings for one block

Section titled “M20-C08 · Override settings for one block”
Core

Write a context manager class Override that changes some keys of a settings dict inside a with block and restores the dict afterwards, also after an exception. A key that did not exist before the block must be removed again. Test it on the thresholds section of data/config.json.

Expected output
inside: 0.3 3
after: 0.5 False
error: report failed | max_discount = 0.2
Starter
import json
class Override:
def __init__(self, settings: dict[str, Any], **changes: Any) -> None:
self.settings = settings
self.changes = changes
# TODO: __enter__ saves the old values (or "missing"), applies changes, returns the dict
# TODO: __exit__ restores the old values and deletes keys that were missing
with open("data/config.json", encoding="utf-8") as f:
thresholds = json.load(f)["thresholds"]
# TODO: inside a with block, print churn_probability and the new key min_tenure
# TODO: after the block, print churn_probability and "min_tenure" in thresholds
# TODO: show that the dict is restored after an error inside the block
Hint 1

Use a unique marker object for “this key did not exist”: _MISSING = object(). dict.get(key, _MISSING) returns it for a missing key.

Hint 2

In __exit__, loop over the saved values: delete the key when the saved value is _MISSING, otherwise put the old value back. Return None, so exceptions continue.

Solution
import json
_MISSING = object() # a marker that no real setting can equal
class Override:
def __init__(self, settings: dict[str, Any], **changes: Any) -> None:
self.settings = settings
self.changes = changes
self._saved: dict[str, Any] = {}
def __enter__(self) -> dict[str, Any]:
self._saved = {k: self.settings.get(k, _MISSING) for k in self.changes}
self.settings.update(self.changes)
return self.settings
def __exit__(self, exc_type, exc_value, traceback) -> None:
for key, old in self._saved.items():
if old is _MISSING:
del self.settings[key]
else:
self.settings[key] = old
with open("data/config.json", encoding="utf-8") as f:
thresholds = json.load(f)["thresholds"]
original = dict(thresholds)
with Override(thresholds, churn_probability=0.3, min_tenure=3) as t:
print("inside:", t["churn_probability"], t["min_tenure"])
print("after: ", thresholds["churn_probability"], "min_tenure" in thresholds)
try:
with Override(thresholds, max_discount=0.5):
raise RuntimeError("report failed")
except RuntimeError as error:
print("error: ", error, "| max_discount =", thresholds["max_discount"])
assert thresholds == original
Output
inside: 0.3 3
after: 0.5 False
error: report failed | max_discount = 0.2

How it works:

  1. __enter__ saves the current value of each key that will change, or the _MISSING marker when the key is new. Then it applies the changes and returns the dict for as.
  2. __exit__ runs after the block in every case. It puts old values back and deletes keys that did not exist.
  3. In the second block, the RuntimeError passes through __exit__, which restores max_discount, and returns None, so the error reaches the except clause.
  4. _MISSING is a fresh object(), so it cannot be confused with a real setting, not even None.

Alternative: module 11’s @contextlib.contextmanager writes the same thing as a generator function with try/finally around one yield. For a dict of settings, unittest.mock.patch.dict(thresholds, {...}) does it too, and tests use it often.

M20-C09 · Choose the special methods for a feature store

Section titled “M20-C09 · Choose the special methods for a feature store”
Core

Choose a method and justify it. A team needs a FeatureStore class for model inputs. The requirements:

  1. len(store) gives the number of features.
  2. store["age"] gives the values of a feature; an unknown name raises KeyError.
  3. "age" in store must be fast (no loop over the features).
  4. for name in store gives the feature names in the order they were added.
  5. print(store) shows FeatureStore(['age', 'tenure_months']).
  6. Two stores with the same features and values compare equal.

List the special methods you need and the reason for each one. Then write the class and test it on the first five customers of data/customers.csv. One requirement has a side effect on hashing: say which one.

Expected output
FeatureStore(['age', 'tenure_months']) 2
[18.0, 23.0, 24.0, 38.0, 41.0]
True False ['age', 'tenure_months']
None
Starter
class FeatureStore:
def __init__(self) -> None:
self._features: dict[str, list[float]] = {}
def add(self, name: str, values: list[float]) -> None:
self._features[name] = values
# TODO: the special methods for requirements 1-6
with open("data/customers.csv", encoding="utf-8", newline="") as f:
rows = list(islice(csv.DictReader(f), 5))
store = FeatureStore()
store.add("age", [float(r["age"]) for r in rows])
store.add("tenure_months", [float(r["tenure_months"]) for r in rows])
# TODO: print store, len(store), store["age"], "age" in store, "plan" in store, list(store)
Hint 1

Requirement → method: 1 __len__, 2 __getitem__, 3 __contains__, 4 __iter__, 5 __repr__, 6 __eq__.

Hint 2

A dict keeps insertion order and has fast key lookup. Delegate each method to self._features.

Solution
class FeatureStore:
def __init__(self) -> None:
self._features: dict[str, list[float]] = {}
def add(self, name: str, values: list[float]) -> None:
self._features[name] = values
def __repr__(self) -> str: # requirement 5
return f"FeatureStore({list(self._features)!r})"
def __len__(self) -> int: # requirement 1
return len(self._features)
def __getitem__(self, name: str) -> list[float]: # requirement 2
return self._features[name]
def __contains__(self, name: object) -> bool: # requirement 3
return name in self._features
def __iter__(self) -> Iterator[str]: # requirement 4
return iter(self._features)
def __eq__(self, other: object) -> bool: # requirement 6
if not isinstance(other, FeatureStore):
return NotImplemented
return self._features == other._features
with open("data/customers.csv", encoding="utf-8", newline="") as f:
rows = list(islice(csv.DictReader(f), 5))
store = FeatureStore()
store.add("age", [float(r["age"]) for r in rows])
store.add("tenure_months", [float(r["tenure_months"]) for r in rows])
print(store, len(store))
print(store["age"])
print("age" in store, "plan" in store, list(store))
print(FeatureStore.__hash__)
assert len(store) == 2 and list(store) == ["age", "tenure_months"]
twin = FeatureStore()
twin.add("age", store["age"])
twin.add("tenure_months", store["tenure_months"])
assert twin == store
Output
FeatureStore(['age', 'tenure_months']) 2
[18.0, 23.0, 24.0, 38.0, 41.0]
True False ['age', 'tenure_months']
None

How it works:

  1. __len__, __getitem__, __iter__ and __repr__ cover requirements 1, 2, 4 and 5. Each delegates to the dict, which already does the job: self._features[name] raises KeyError for an unknown name.
  2. __contains__ is a deliberate choice. Without it, in would fall back to __iter__ and scan the names one by one. The dict lookup is a hash lookup, which takes constant time.
  3. __eq__ covers requirement 6 and has the side effect: Python sets __hash__ to None, so stores are unhashable. That is correct, because add() changes a store.
  4. __iter__ yields names, and __contains__ tests names, so for and in agree, as they do for a dict.

Alternative: inherit from collections.abc.Mapping and write only __getitem__, __len__ and __iter__. The base class adds __contains__, keys(), items(), values(), get() and __eq__. Its __contains__ is fast here, because it calls __getitem__ and catches KeyError instead of looping.

M20-C10 · Predict comparisons without total_ordering

Section titled “M20-C10 · Predict comparisons without total_ordering”
Core

Predict the output: this Score class has __eq__ and __lt__ but no @total_ordering. Each method prints when it runs. Write down every line that the code prints.

Starter
class Score:
def __init__(self, value: float) -> None:
self.value = value
def __eq__(self, other: object) -> bool:
print("eq")
return isinstance(other, Score) and self.value == other.value
def __lt__(self, other: "Score") -> bool:
print(f"lt({self.value}, {other.value})")
return self.value < other.value
a, b = Score(0.815), Score(0.845)
print(a < b)
print(a > b)
print(a != b)
try:
print(a <= b)
except TypeError as error:
print("TypeError:", error)

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.
Hint 1

Score has no __gt__. For a > b, Python tries the reflected comparison b < a.

Hint 2

!= uses the default __ne__, which calls __eq__ and inverts it. Nothing provides __le__, and its reflection __ge__ is missing too.

Solution
class Score:
def __init__(self, value: float) -> None:
self.value = value
def __eq__(self, other: object) -> bool:
print("eq")
return isinstance(other, Score) and self.value == other.value
def __lt__(self, other: "Score") -> bool:
print(f"lt({self.value}, {other.value})")
return self.value < other.value
a, b = Score(0.815), Score(0.845)
print(a < b)
print(a > b)
print(a != b)
try:
print(a <= b)
except TypeError as error:
print("TypeError:", error)
assert not hasattr(Score, "__le__") or Score.__le__ is object.__le__
Output
lt(0.815, 0.845)
True
lt(0.845, 0.815)
False
eq
True
TypeError: '<=' not supported between instances of 'Score' and 'Score'

How it works:

  1. a < b calls a.__lt__(b) directly.
  2. a > b: Score inherits object.__gt__, which returns NotImplemented. Python tries the reflection b.__lt__(a), so it prints lt(0.845, 0.815) and the answer False.
  3. a != b: the default __ne__ calls __eq__ (which prints eq) and inverts its False.
  4. a <= b: __le__ and its reflection b.__ge__(a) both return NotImplemented, so Python raises TypeError. @total_ordering would add both.
  5. The assert confirms that Score only has the __le__ inherited from object.
Core

Fix the bug: a refund report keeps a list of refunds, with None for orders whose refund is not known yet. Checking Money(0) in refunds crashes with AttributeError: 'NoneType' object has no attribute 'cents'. Fix __eq__ so that comparisons with other types work.

Expected output
True
False False
1
Starter
class Money:
def __init__(self, cents: int) -> None:
self.cents = cents
def __repr__(self) -> str:
return f"Money({self.cents})"
def __eq__(self, other: "Money") -> bool:
return self.cents == other.cents
def __hash__(self) -> int:
return hash(self.cents)
refunds = [Money(1499), None, Money(0), Money(22410)]
print(Money(0) in refunds)
print(Money(0) == None, Money(1499) == 14.99) # noqa: E711
print(refunds.count(None))
Hint 1

in compares Money(0) with each item in order, so the second comparison is Money(0) == None.

Hint 2

Check the type first. For any other type, return NotImplemented.

Solution
class Money:
def __init__(self, cents: int) -> None:
self.cents = cents
def __repr__(self) -> str:
return f"Money({self.cents})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, Money):
return NotImplemented
return self.cents == other.cents
def __hash__(self) -> int:
return hash(self.cents)
refunds = [Money(1499), None, Money(0), Money(22410)]
print(Money(0) in refunds)
print(Money(0) == None, Money(1499) == 14.99) # noqa: E711
print(refunds.count(None))
assert Money(0) in refunds and (Money(0) != None) # noqa: E711
Output
True
False False
1

How it works:

  1. Money(0) in refunds compares with each item in turn. The old __eq__ read other.cents from None and crashed.
  2. The fixed __eq__ returns NotImplemented for None and for the float 14.99. Python tries the reflected comparison, which also declines, and falls back to identity: False.
  3. refunds.count(None) compares None with each item. For None == Money(...), None declines and Python asks Money.__eq__, which must not crash either.
  4. The # noqa: E711 comments silence the linter rule “compare with None using is”, because this test compares with None on purpose.

Alternative: return isinstance(other, Money) and self.cents == other.cents also avoids the crash, but it returns False instead of NotImplemented. Another class could then never define a comparison with Money. Prefer NotImplemented.

M20-C12 · Compose cleaning steps into one callable

Section titled “M20-C12 · Compose cleaning steps into one callable”
Core

Write a class Compose that chains cleaning functions: Compose(f, g, h)(value) returns h(g(f(value))). It must support len() (the number of steps) and show the step names in its repr. Clean the first eight lines of data/messy_names.txt with four steps: normalize the Unicode form to NFC (module 02), strip the ends, collapse inner spaces and title-case the name.

Expected output
Compose(nfc, strip, collapse_spaces, title) 4
José García
Zoë O'Brien
François Dupont
Björk Guðmundsdóttir
Anna-Lena Müller
Søren Kierkegaard
Mei Chen
José García
Starter
def nfc(text: str) -> str:
return unicodedata.normalize("NFC", text)
def collapse_spaces(text: str) -> str:
return re.sub(r"\s+", " ", text)
class Compose:
def __init__(self, *steps: Callable[[Any], Any]) -> None:
self.steps = steps
# TODO: __repr__ -> Compose(nfc, strip, collapse_spaces, title)
# TODO: __len__ and __call__
clean_name = Compose(nfc, str.strip, collapse_spaces, str.title)
with open("data/messy_names.txt", encoding="utf-8") as f:
names = [line.rstrip("\n") for line in islice(f, 8)]
# TODO: print clean_name, len(clean_name) and the cleaned names
Hint 1

In __call__, loop over the steps: value = step(value), then return value.

Hint 2

Functions and methods such as str.strip have a __name__ attribute. Use getattr(step, "__name__", repr(step)) so a callable object without one still shows something.

Solution
def nfc(text: str) -> str:
return unicodedata.normalize("NFC", text)
def collapse_spaces(text: str) -> str:
return re.sub(r"\s+", " ", text)
class Compose:
def __init__(self, *steps: Callable[[Any], Any]) -> None:
self.steps = steps
def __repr__(self) -> str:
names = ", ".join(getattr(s, "__name__", repr(s)) for s in self.steps)
return f"Compose({names})"
def __len__(self) -> int:
return len(self.steps)
def __call__(self, value: Any) -> Any:
for step in self.steps:
value = step(value)
return value
clean_name = Compose(nfc, str.strip, collapse_spaces, str.title)
with open("data/messy_names.txt", encoding="utf-8") as f:
names = [line.rstrip("\n") for line in islice(f, 8)]
print(clean_name, len(clean_name))
for name in map(clean_name, names):
print(name)
assert clean_name(" josé GARCÍA ") == "José García"
assert len(set(map(clean_name, names))) < len(names) # duplicates now match
Output
Compose(nfc, strip, collapse_spaces, title) 4
José García
Zoë O'Brien
François Dupont
Björk Guðmundsdóttir
Anna-Lena Müller
Søren Kierkegaard
Mei Chen
José García

How it works:

  1. Compose stores the steps in a tuple. __call__ passes the value through each step in order.
  2. str.strip and str.title are unbound methods: str.title("ab") is the same as "ab".title(), so they work as one-argument functions.
  3. map(clean_name, names) treats the object as a function. Lines 1 and 8 now give the same name, so the last assert finds a duplicate that the raw text hid. Line 8 stores “José García” in the decomposed NFD form (a letter plus a combining accent). Without the nfc step, str.title() treats the combining accent as a word break and returns GarcíA.
  4. __len__ makes Compose truthy only when it has steps.

Alternative: functools.reduce(lambda v, f: f(v), steps, value) applies the steps in one line, but it has no repr and no length. scikit-learn’s Pipeline and torchvision’s transforms.Compose are classes for exactly this reason.

M20-C13 · Show only the changed parameters in the repr

Section titled “M20-C13 · Show only the changed parameters in the repr”
Core

scikit-learn prints KNeighborsClassifier(n_neighbors=3) and leaves out parameters that keep their default value. Write BaseEstimator.__repr__ that does the same: compare each value from get_params() with the default in the signature of __init__. Test it on the two estimators below.

Expected output
KNNClassifier()
KNNClassifier(n_neighbors=15)
KNNClassifier(n_neighbors=3, weights='distance')
StandardScaler(with_std=False)
Starter
class BaseEstimator:
@classmethod
def _signature(cls) -> dict[str, inspect.Parameter]:
params = dict(inspect.signature(cls.__init__).parameters)
params.pop("self")
return params
def get_params(self) -> dict[str, Any]:
return {name: getattr(self, name) for name in self._signature()}
# TODO: __repr__ that shows only the parameters that differ from their default
class KNNClassifier(BaseEstimator):
def __init__(self, n_neighbors: int = 5, weights: str = "uniform") -> None:
self.n_neighbors = n_neighbors
self.weights = weights
class StandardScaler(BaseEstimator):
def __init__(self, with_mean: bool = True, with_std: bool = True) -> None:
self.with_mean = with_mean
self.with_std = with_std
# TODO: print KNNClassifier(), KNNClassifier(n_neighbors=15),
# KNNClassifier(3, "distance") and StandardScaler(with_std=False)
Hint 1

self._signature()[name].default is the default value of a parameter.

Hint 2

Keep a pair when value != default. Join the kept pairs with ", " and f"{k}={v!r}".

Solution
class BaseEstimator:
@classmethod
def _signature(cls) -> dict[str, inspect.Parameter]:
params = dict(inspect.signature(cls.__init__).parameters)
params.pop("self")
return params
def get_params(self) -> dict[str, Any]:
return {name: getattr(self, name) for name in self._signature()}
def __repr__(self) -> str:
defaults = {n: p.default for n, p in self._signature().items()}
changed = {k: v for k, v in self.get_params().items() if v != defaults[k]}
args = ", ".join(f"{k}={v!r}" for k, v in changed.items())
return f"{type(self).__name__}({args})"
class KNNClassifier(BaseEstimator):
def __init__(self, n_neighbors: int = 5, weights: str = "uniform") -> None:
self.n_neighbors = n_neighbors
self.weights = weights
class StandardScaler(BaseEstimator):
def __init__(self, with_mean: bool = True, with_std: bool = True) -> None:
self.with_mean = with_mean
self.with_std = with_std
for model in (
KNNClassifier(),
KNNClassifier(n_neighbors=15),
KNNClassifier(3, "distance"),
StandardScaler(with_std=False),
):
print(model)
assert repr(KNNClassifier(n_neighbors=5)) == "KNNClassifier()"
assert eval(repr(KNNClassifier(3, "distance"))).get_params() == {
"n_neighbors": 3,
"weights": "distance",
}
Output
KNNClassifier()
KNNClassifier(n_neighbors=15)
KNNClassifier(n_neighbors=3, weights='distance')
StandardScaler(with_std=False)

How it works:

  1. inspect.signature(cls.__init__) describes the parameters of __init__. Each Parameter has a .default.
  2. The repr keeps only the parameters whose current value differs from the default.
  3. KNNClassifier(n_neighbors=5) prints as KNNClassifier(): the output is shorter, and it still rebuilds an equal model, because the defaults fill in the rest.
  4. The last assert proves that the short repr is still valid code.

Alternative: show every parameter, as the lesson’s BaseEstimator does. It is longer but never hides a value. scikit-learn chooses the short form by default; sklearn.set_config(print_changed_only=False) switches to the long one.

M20-X01 · A confusion matrix you can index and add

Section titled “M20-X01 · A confusion matrix you can index and add”
Challenge

Module 01 flagged customers at risk with a rule: churn is predicted when tenure_months <= 6 and logins_last_30d <= 3. Evaluate the rule on data/customers.csv in 5 folds of 1,000 rows each, and combine the folds into one confusion matrix: the table of counts of (actual label, predicted label) pairs. Write a class ConfusionMatrix that:

  1. builds itself from y_true and y_pred with a class method from_predictions;
  2. returns one count for a tuple key: cm[1, 0] is the number of churners predicted as “stay”;
  3. supports len(cm) (the number of samples), ==, + and sum() over folds;
  4. has a short repr and a __str__ that prints a 2 × 2 table;
  5. has accuracy, precision and recall for the label 1.

Print the size and the true positives of each fold, then the total table and the three scores.

Expected output
fold 1: 1000 rows, true positives = 0
fold 2: 1000 rows, true positives = 0
fold 3: 1000 rows, true positives = 0
fold 4: 1000 rows, true positives = 1
fold 5: 1000 rows, true positives = 62
ConfusionMatrix(n=5000, labels=(0, 1))
actual \ predicted 0 1
0 4010 27
1 900 63
accuracy 0.815 precision 0.700 recall 0.065
Starter
class ConfusionMatrix:
def __init__(
self, counts: dict[tuple[Any, Any], int], labels: tuple = (0, 1)
) -> None:
self.labels = tuple(labels)
pairs = [(a, p) for a in self.labels for p in self.labels]
self.counts = {pair: counts.get(pair, 0) for pair in pairs}
# TODO: from_predictions (classmethod), __repr__, __str__
# TODO: __getitem__ with an (actual, predicted) key, __len__, __eq__
# TODO: __add__ and __radd__
# TODO: accuracy, precision and recall (label 1)
with open("data/customers.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
y_true = [int(r["churned"]) for r in rows]
y_pred = [
int(int(r["tenure_months"]) <= 6 and int(r["logins_last_30d"]) <= 3) for r in rows
]
# TODO: one ConfusionMatrix per fold of 1,000 rows; print len and cm[1, 1] per fold
# TODO: total = sum(folds); print total and the three scores
Hint 1

Counter(zip(y_true, y_pred)) counts the pairs in one line. Pass it to cls(...).

Hint 2

cm[1, 0] passes the tuple (1, 0) as one key to __getitem__. For __add__, add the counts key by key, after checking that both matrices use the same labels.

Hint 3

Precision is TPTP+FP\frac{TP}{TP + FP} = cm[1, 1] / (cm[1, 1] + cm[0, 1]). Recall is TPTP+FN\frac{TP}{TP + FN} = cm[1, 1] / (cm[1, 1] + cm[1, 0]).

Solution
class ConfusionMatrix:
"""Counts of (actual, predicted) label pairs."""
def __init__(
self, counts: dict[tuple[Any, Any], int], labels: tuple = (0, 1)
) -> None:
self.labels = tuple(labels)
pairs = [(a, p) for a in self.labels for p in self.labels]
self.counts = {pair: counts.get(pair, 0) for pair in pairs}
@classmethod
def from_predictions(
cls, y_true: list[Any], y_pred: list[Any], labels: tuple = (0, 1)
) -> Self:
return cls(Counter(zip(y_true, y_pred, strict=True)), labels)
def __repr__(self) -> str:
return f"ConfusionMatrix(n={len(self)}, labels={self.labels!r})"
def __str__(self) -> str:
lines = ["actual \\ predicted " + " ".join(f"{p:>6}" for p in self.labels)]
for a in self.labels:
cells = " ".join(f"{self[a, p]:>6}" for p in self.labels)
lines.append(f"{a!s:>18} {cells}")
return "\n".join(lines)
def __getitem__(self, key: tuple[Any, Any]) -> int:
return self.counts[key] # KeyError for an unknown pair of labels
def __len__(self) -> int:
return sum(self.counts.values())
def __eq__(self, other: object) -> bool:
if not isinstance(other, ConfusionMatrix):
return NotImplemented
return (self.labels, self.counts) == (other.labels, other.counts)
def __add__(self, other: object) -> "ConfusionMatrix":
if not isinstance(other, ConfusionMatrix):
return NotImplemented
if self.labels != other.labels:
raise ValueError(f"labels differ: {self.labels} and {other.labels}")
merged = {key: self[key] + other[key] for key in self.counts}
return ConfusionMatrix(merged, self.labels)
def __radd__(self, other: object) -> "ConfusionMatrix":
return self if other == 0 else NotImplemented
@property
def accuracy(self) -> float:
return sum(self[label, label] for label in self.labels) / len(self)
@property
def precision(self) -> float:
return self[1, 1] / (self[1, 1] + self[0, 1])
@property
def recall(self) -> float:
return self[1, 1] / (self[1, 1] + self[1, 0])
with open("data/customers.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
y_true = [int(r["churned"]) for r in rows]
y_pred = [
int(int(r["tenure_months"]) <= 6 and int(r["logins_last_30d"]) <= 3) for r in rows
]
folds = [
ConfusionMatrix.from_predictions(y_true[i : i + 1000], y_pred[i : i + 1000])
for i in range(0, len(rows), 1000)
]
for number, cm in enumerate(folds, start=1):
print(f"fold {number}: {len(cm)} rows, true positives = {cm[1, 1]}")
total = sum(folds)
print(repr(total))
print(total)
print(
f"accuracy {total.accuracy:.3f} precision {total.precision:.3f} "
f"recall {total.recall:.3f}"
)
assert total == ConfusionMatrix.from_predictions(y_true, y_pred)
assert len(total) == 5000 and total[1, 0] + total[1, 1] == sum(y_true)
Output
fold 1: 1000 rows, true positives = 0
fold 2: 1000 rows, true positives = 0
fold 3: 1000 rows, true positives = 0
fold 4: 1000 rows, true positives = 1
fold 5: 1000 rows, true positives = 62
ConfusionMatrix(n=5000, labels=(0, 1))
actual \ predicted 0 1
0 4010 27
1 900 63
accuracy 0.815 precision 0.700 recall 0.065

How it works:

  1. from_predictions counts the (actual, predicted) pairs with Counter and hands them to __init__, which fills every pair of labels, with 0 for pairs that never occur.
  2. cm[1, 1] passes the tuple (1, 1) to __getitem__. A dict with tuple keys does the lookup.
  3. sum(folds) starts with 0 + folds[0], which __radd__ handles, and then adds matrix by matrix with __add__. The first assert proves that the sum of the folds equals one matrix built from all rows.
  4. The file is in signup order, so fold 5 holds the newest customers. Almost all short tenures are there, and the rule fires almost only in that fold.
  5. When the rule fires, it is right 70% of the time (precision 0.700). But it finds only 63 of the 963 churners (recall 0.065). Its accuracy, 0.815, is barely above the baseline that predicts “stay” for everyone: 4,037 / 5,000 = 0.807. A trained model in module 36 does much better.

Alternative: scikit-learn’s sklearn.metrics.confusion_matrix(y_true, y_pred) returns a NumPy array, and cm[1, 1] works on it too, because NumPy’s __getitem__ also accepts a tuple key. Adding two arrays adds them element by element, so sum() over folds works there as well.

M20-X02 · Word counts that merge across chunks

Section titled “M20-X02 · Word counts that merge across chunks”
Challenge

Count the words of the review texts in data/reviews.csv in chunks of 1,000 reviews, then merge the chunk counts, as a job would do with a file too big for memory or with several worker processes. Write a class FrequencyTable that:

  1. builds itself from texts with a class method from_texts (lowercase, words matched by the regex [a-z']+);
  2. returns the count of a word with table["great"], and 0 for a word it never saw;
  3. supports len() (the number of distinct words), in, ==, + and sum();
  4. iterates over the words from the most to the least frequent, with ties in alphabetical order;
  5. has a repr that shows the number of distinct words and of tokens.

Print the three chunk tables, the merged table, the five most frequent words with their counts and the counts of "refund" and "warranty".

Expected output
FrequencyTable(375 words, 16,359 tokens)
FrequencyTable(368 words, 16,251 tokens)
FrequencyTable(377 words, 15,817 tokens)
FrequencyTable(383 words, 48,427 tokens)
[('the', 4052), ('is', 1772), ('it', 1499), ('to', 1055), ('this', 1047)]
refund: 160 | warranty: 0 False
Starter
class FrequencyTable:
def __init__(self, counts: dict[str, int] | None = None) -> None:
self._counts = Counter(counts or {})
# TODO: from_texts (classmethod), total (property), __repr__
# TODO: __len__, __getitem__ (0 for a missing word), __contains__, __iter__
# TODO: __eq__, __add__, __radd__
with open("data/reviews.csv", encoding="utf-8", newline="") as f:
texts = [row["text"] for row in csv.DictReader(f)]
# TODO: chunk tables for texts[0:1000], texts[1000:2000], texts[2000:3000]
# TODO: merge them with sum(), print the results and check against one pass
Hint 1

re.findall(r"[a-z']+", text.lower()) returns the words of one text. A Counter adds them up, and two Counter objects add with +.

Hint 2

For the iteration order, sort the words with the key lambda w: (-self._counts[w], w): a higher count first, then alphabetical.

Hint 3

__contains__ must not use __getitem__, because __getitem__ returns 0 for every word. Test word in self._counts instead.

Solution
class FrequencyTable:
"""Word counts that can be merged with + and sum()."""
def __init__(self, counts: dict[str, int] | None = None) -> None:
self._counts = Counter(counts or {})
@classmethod
def from_texts(cls, texts: Iterable[str]) -> Self:
counts: Counter[str] = Counter()
for text in texts:
counts.update(re.findall(r"[a-z']+", text.lower()))
return cls(counts)
@property
def total(self) -> int:
return sum(self._counts.values())
def __repr__(self) -> str:
return f"FrequencyTable({len(self):,} words, {self.total:,} tokens)"
def __len__(self) -> int:
return len(self._counts)
def __getitem__(self, word: str) -> int:
return self._counts.get(word, 0)
def __contains__(self, word: object) -> bool:
return word in self._counts
def __iter__(self) -> Iterator[str]:
yield from sorted(self._counts, key=lambda w: (-self._counts[w], w))
def __eq__(self, other: object) -> bool:
if not isinstance(other, FrequencyTable):
return NotImplemented
return self._counts == other._counts
def __add__(self, other: object) -> "FrequencyTable":
if not isinstance(other, FrequencyTable):
return NotImplemented
return FrequencyTable(self._counts + other._counts)
def __radd__(self, other: object) -> "FrequencyTable":
return self if other == 0 else NotImplemented
with open("data/reviews.csv", encoding="utf-8", newline="") as f:
texts = [row["text"] for row in csv.DictReader(f)]
chunks = [
FrequencyTable.from_texts(texts[i : i + 1000]) for i in range(0, len(texts), 1000)
]
for chunk in chunks:
print(chunk)
table = sum(chunks)
print(table)
print([(word, table[word]) for word in islice(table, 5)])
print("refund:", table["refund"], "| warranty:", table["warranty"], "warranty" in table)
assert table == FrequencyTable.from_texts(texts)
assert table.total == sum(chunk.total for chunk in chunks)
Output
FrequencyTable(375 words, 16,359 tokens)
FrequencyTable(368 words, 16,251 tokens)
FrequencyTable(377 words, 15,817 tokens)
FrequencyTable(383 words, 48,427 tokens)
[('the', 4052), ('is', 1772), ('it', 1499), ('to', 1055), ('this', 1047)]
refund: 160 | warranty: 0 False

How it works:

  1. from_texts lowercases each text and extracts its words with the regex, then counts them in a Counter.
  2. __getitem__ uses .get(word, 0), so an unseen word counts 0 and never raises. Because of that, __contains__ must ask the dict directly; the fallback through __iter__ would also work but scans every word.
  3. sum(chunks) merges the three tables. Counter + Counter adds the counts word by word. The first assert proves that merging chunks gives the same table as one pass over all texts.
  4. __iter__ sorts by count, then by word, so islice(table, 5) gives the top five.
  5. “warranty” never appears in the review texts, so its count is 0 and in is False. The table never stores the 0, so len(table) does not grow when you ask for a missing word.

Alternative: Counter alone does most of this (+, most_common(), 0 for missing keys). The class adds a clear repr, a fixed iteration order and a place for future rules such as stop words. In module 41, scikit-learn’s CountVectorizer does the counting for a whole corpus.

M20-X03 · A column with vectorized operators and masks

Section titled “M20-X03 · A column with vectorized operators and masks”
Challenge

Build a tiny pandas-like Column to see how df["price"] / df["sqft"] and df[df["sqft"] > 2000] work inside. Use the first 8 houses of data/houses.csv. Requirements:

  1. Arithmetic +, -, *, / works element by element with another Column of the same length, and with a number on either side (price / 1000, 1 / sqft).
  2. Comparisons >, <, >=, <= and == return a Column of bool values: a mask.
  3. col[mask] keeps the values where the mask is True; col[i] and col[a:b] work as usual.
  4. if col: raises ValueError, because the truth of a whole column is ambiguous.
  5. len(), iteration, a short repr and a mean() method.

Print the price per square foot, the mask of big houses, the mean price of big and small houses, and what if big: does.

Expected output
Column([453.51, 302.17, 176.98, 240.78, 197.63, 248.63, 236.61, 251.45])
Column('sqft', [True, False, False, False, True, True, False, False])
big: 756,167 small: 394,600
Column('price', [1097.5, 486.5, 223.0]) Column('sqft', [0.41, 0.62, 0.79])
ValueError: The truth value of a Column is ambiguous. Use any() or all()
Starter
import operator
class Column:
def __init__(self, values: Iterable[Any], name: str = "") -> None:
self.values = list(values)
self.name = name
# TODO: __repr__, __len__, __iter__, mean()
# TODO: a helper _apply(other, op) for Column-or-number operands
# TODO: __add__/__radd__, __sub__/__rsub__, __mul__/__rmul__, __truediv__/__rtruediv__
# TODO: __gt__, __lt__, __ge__, __le__, __eq__ returning masks
# TODO: __getitem__ for int, slice and a bool mask; __bool__ raises ValueError
with open("data/houses.csv", encoding="utf-8", newline="") as f:
rows = list(islice(csv.DictReader(f), 8))
price = Column((int(r["price"]) for r in rows), "price")
sqft = Column((int(r["sqft"]) for r in rows), "sqft")
# TODO: price per sqft, big = sqft > 2000, mean price of big and not-big houses
Hint 1

One helper serves every operator: _apply(other, op) returns NotImplemented for an unknown type, pairs the values for a Column and repeats the number for a scalar. operator.add, operator.truediv, operator.gt and the others are the operators as functions.

Hint 2

For a reflected operator, swap the arguments: __rsub__(self, other) computes other - self, so pass lambda a, b: b - a or write _apply(other, op, reflected=True).

Hint 3

A mask has no “not” operator yet. Write __invert__ (the ~ operator, as in pandas) to flip a mask: price[~big].

Solution
import operator
class Column:
"""A list of values with element-wise operators, like a pandas Series."""
def __init__(self, values: Iterable[Any], name: str = "") -> None:
self.values = list(values)
self.name = name
def __repr__(self) -> str:
shown = [round(v, 2) if isinstance(v, float) else v for v in self.values]
prefix = f"{self.name!r}, " if self.name else ""
return f"Column({prefix}{shown!r})"
def __len__(self) -> int:
return len(self.values)
def __iter__(self) -> Iterator[Any]:
return iter(self.values)
def mean(self) -> float:
return statistics.fmean(self.values)
def _apply(self, other: object, op: Callable, reflected: bool = False) -> Any:
if isinstance(other, Column):
if len(other) != len(self):
raise ValueError(f"lengths differ: {len(self)} and {len(other)}")
others = other.values
name = self.name if other.name == self.name else ""
elif isinstance(other, int | float):
others = [other] * len(self)
name = self.name
else:
return NotImplemented
pairs = zip(self.values, others, strict=True)
if reflected:
return Column((op(b, a) for a, b in pairs), name)
return Column((op(a, b) for a, b in pairs), name)
def __add__(self, other: object) -> Any:
return self._apply(other, operator.add)
def __radd__(self, other: object) -> Any:
return self._apply(other, operator.add, reflected=True)
def __sub__(self, other: object) -> Any:
return self._apply(other, operator.sub)
def __rsub__(self, other: object) -> Any:
return self._apply(other, operator.sub, reflected=True)
def __mul__(self, other: object) -> Any:
return self._apply(other, operator.mul)
def __rmul__(self, other: object) -> Any:
return self._apply(other, operator.mul, reflected=True)
def __truediv__(self, other: object) -> Any:
return self._apply(other, operator.truediv)
def __rtruediv__(self, other: object) -> Any:
return self._apply(other, operator.truediv, reflected=True)
def __gt__(self, other: object) -> Any:
return self._apply(other, operator.gt)
def __lt__(self, other: object) -> Any:
return self._apply(other, operator.lt)
def __ge__(self, other: object) -> Any:
return self._apply(other, operator.ge)
def __le__(self, other: object) -> Any:
return self._apply(other, operator.le)
def __eq__(self, other: object) -> Any: # element-wise, like pandas
return self._apply(other, operator.eq)
__hash__ = None # explicit: a Column changes, and == does not return a bool
def __invert__(self) -> "Column":
return Column(not v for v in self.values)
def __getitem__(self, key: "int | slice | Column") -> Any:
if isinstance(key, Column):
if len(key) != len(self):
raise ValueError("mask length differs from column length")
return Column((v for v, keep in zip(self, key) if keep), self.name)
if isinstance(key, slice):
return Column(self.values[key], self.name)
return self.values[key]
def __bool__(self) -> bool:
raise ValueError("The truth value of a Column is ambiguous. Use any() or all()")
with open("data/houses.csv", encoding="utf-8", newline="") as f:
rows = list(islice(csv.DictReader(f), 8))
price = Column((int(r["price"]) for r in rows), "price")
sqft = Column((int(r["sqft"]) for r in rows), "sqft")
per_sqft = price / sqft
print(per_sqft)
big = sqft > 2000
print(big)
print(f"big: {price[big].mean():,.0f} small: {price[~big].mean():,.0f}")
print((price / 1000)[:3], (1000 / sqft)[:3])
try:
if big:
print("unreachable")
except ValueError as error:
print("ValueError:", error)
assert len(price[big]) + len(price[~big]) == len(price)
assert list(sqft == 1610) == [v == 1610 for v in sqft]
Output
Column([453.51, 302.17, 176.98, 240.78, 197.63, 248.63, 236.61, 251.45])
Column('sqft', [True, False, False, False, True, True, False, False])
big: 756,167 small: 394,600
Column('price', [1097.5, 486.5, 223.0]) Column('sqft', [0.41, 0.62, 0.79])
ValueError: The truth value of a Column is ambiguous. Use any() or all()

How it works:

  1. _apply is the single place that knows the rules: a Column pairs values, a number is repeated, anything else returns NotImplemented.
  2. price / sqft calls __truediv__ with a Column. The result has no name, because the two names differ (pandas uses the same rule). 1000 / sqft starts with int.__truediv__, which declines, so Python calls sqft.__rtruediv__(1000), which computes 1000 / value for each value.
  3. sqft > 2000 calls __gt__ and returns a mask. price[big] passes the mask to __getitem__, which keeps the matching prices. ~big calls __invert__.
  4. __eq__ returns a Column, not a bool, so the class sets __hash__ = None explicitly. Python would do it anyway, because the class defines __eq__; writing it shows the intent.
  5. __bool__ raises, so if big: fails loudly instead of guessing. pandas and NumPy raise the same kind of ValueError.

Alternative: this is exactly what pandas (module 24) and NumPy (module 23) do, in fast compiled code. With pandas: df["price"] / df["sqft"] and df[df["sqft"] > 2000]["price"].mean().

M20-X04 · A parameter grid with len and lazy indexing

Section titled “M20-X04 · A parameter grid with len and lazy indexing”
Challenge

A hyperparameter search tries every combination of a grid. scikit-learn’s ParameterGrid supports len() and indexing without building the list of combinations, so a search can split the work by position. Write a class ParamGrid that:

  1. takes a dict such as {"scaler__with_std": [True, False], "knn__n_neighbors": [1, 5, 15, 25, 45]};
  2. gives len(grid) as the product of the list lengths;
  3. computes grid[i] directly from i (negative indexes too, IndexError past the end) and grid[a:b] as a list;
  4. iterates in the same order as itertools.product, the last key changing fastest;
  5. answers params in grid without looping over the combinations.

Print the length, the first, last and 8th combinations, a slice, a membership test, and the length and one combination of a grid with a billion combinations.

Expected output
ParamGrid(scaler__with_std: 2, knn__weights: 2, knn__n_neighbors: 5; 20 combinations)
{'scaler__with_std': True, 'knn__weights': 'uniform', 'knn__n_neighbors': 1}
{'scaler__with_std': False, 'knn__weights': 'distance', 'knn__n_neighbors': 45}
{'scaler__with_std': True, 'knn__weights': 'distance', 'knn__n_neighbors': 15}
[25, 45, 1, 5, 15]
True False
1,000,000,000 {'a': 123, 'b': 456, 'c': 789}
Starter
class ParamGrid:
def __init__(self, grid: dict[str, Iterable[Any]]) -> None:
self.grid = {name: list(values) for name, values in grid.items()}
# TODO: __repr__, __len__ (math.prod)
# TODO: __getitem__(int) with divmod, from the last key to the first; slices
# TODO: __iter__ with itertools.product, __contains__ without a loop over combinations
grid = ParamGrid({
"scaler__with_std": [True, False],
"knn__weights": ["uniform", "distance"],
"knn__n_neighbors": [1, 5, 15, 25, 45],
})
# TODO: print len(grid), grid[0], grid[-1], grid[7], grid[3:5]
# TODO: test membership; build a 1000 x 1000 x 1000 grid and index it
Hint 1

Think of the index as a number written in mixed bases. For the last key with 5 values, i, pos = divmod(i, 5) gives its position pos and the rest of the index for the keys before it.

Hint 2

For a slice, range(len(self))[key] turns the slice into the exact positions, including negative and stepped ones. Then build [self[i] for i in positions].

Hint 3

params in grid is true when params is a dict with exactly the grid’s keys and every value appears in the list of its key.

Solution
class ParamGrid:
"""All combinations of a parameter grid, computed on demand."""
def __init__(self, grid: dict[str, Iterable[Any]]) -> None:
self.grid = {name: list(values) for name, values in grid.items()}
def __repr__(self) -> str:
sizes = ", ".join(f"{k}: {len(v)}" for k, v in self.grid.items())
return f"ParamGrid({sizes}; {len(self):,} combinations)"
def __len__(self) -> int:
return math.prod(len(values) for values in self.grid.values())
def __getitem__(self, key: int | slice) -> Any:
if isinstance(key, slice):
return [self[i] for i in range(len(self))[key]]
n = len(self)
if key < 0:
key += n
if not 0 <= key < n:
raise IndexError("ParamGrid index out of range")
combo = {}
for name in reversed(self.grid): # the last key changes fastest
key, pos = divmod(key, len(self.grid[name]))
combo[name] = self.grid[name][pos]
return {name: combo[name] for name in self.grid} # original key order
def __iter__(self) -> Iterator[dict[str, Any]]:
names = list(self.grid)
for values in product(*self.grid.values()):
yield dict(zip(names, values, strict=True))
def __contains__(self, params: object) -> bool:
return (
isinstance(params, dict)
and params.keys() == self.grid.keys()
and all(params[k] in self.grid[k] for k in self.grid)
)
grid = ParamGrid({
"scaler__with_std": [True, False],
"knn__weights": ["uniform", "distance"],
"knn__n_neighbors": [1, 5, 15, 25, 45],
})
print(grid)
print(grid[0])
print(grid[-1])
print(grid[7])
print([p["knn__n_neighbors"] for p in grid[3:8]])
candidate = {
"scaler__with_std": False,
"knn__weights": "distance",
"knn__n_neighbors": 15,
}
print(candidate in grid, {**candidate, "knn__n_neighbors": 3} in grid)
huge = ParamGrid({"a": range(1000), "b": range(1000), "c": range(1000)})
print(f"{len(huge):,}", huge[123_456_789])
assert list(grid) == [grid[i] for i in range(len(grid))]
assert grid[len(grid) - 1] == grid[-1]
Output
ParamGrid(scaler__with_std: 2, knn__weights: 2, knn__n_neighbors: 5; 20 combinations)
{'scaler__with_std': True, 'knn__weights': 'uniform', 'knn__n_neighbors': 1}
{'scaler__with_std': False, 'knn__weights': 'distance', 'knn__n_neighbors': 45}
{'scaler__with_std': True, 'knn__weights': 'distance', 'knn__n_neighbors': 15}
[25, 45, 1, 5, 15]
True False
1,000,000,000 {'a': 123, 'b': 456, 'c': 789}

How it works:

  1. __len__ multiplies the list lengths: 2 × 2 × 5 = 20.
  2. __getitem__ peels off one position per key with divmod, starting with the last key, which changes fastest. This is how you write a number in a mixed base. It needs no list of combinations, so huge[123_456_789] is instant although huge has a billion combinations.
  3. A slice becomes the exact positions through range(len(self))[key], which handles negative and stepped slices for free.
  4. __iter__ uses itertools.product, which produces the same order. The first assert proves that iteration and indexing agree.
  5. __contains__ checks the keys and each value; it never loops over the 20 combinations, let alone a billion.

Alternative: sklearn.model_selection.ParameterGrid does this, and GridSearchCV (module 37) uses it. It also accepts a list of grids.

M20-X05 · Running statistics you can update and merge

Section titled “M20-X05 · Running statistics you can update and merge”
Challenge

Compute the mean and the population standard deviation of sensor S1’s temperature_c in data/sensors.csv without storing the values. Process each day separately, as 14 workers might, and merge the 14 daily results. Write a class RunningStats that:

  1. adds one value with a named method, stats.add(value), using Welford’s algorithm from module 18, and returns self;
  2. merges two results with a + b into a new object, and supports sum(). Use + only for merging: adding one number is a different operation, so it gets a name;
  3. has len() (the count), mean, std and a repr.

Check the merged result against statistics.fmean() and statistics.pstdev() on all values.

The update rules, for a new value xx and for two parts aa and bb with δ=xˉb−xˉa\delta = \bar x_b - \bar x_a:

n←n+1,xˉ←xˉ+x−xˉoldn,M2←M2+(x−xˉold)(x−xˉnew)n \leftarrow n + 1,\quad \bar x \leftarrow \bar x + \frac{x - \bar x_{\text{old}}}{n},\quad M_2 \leftarrow M_2 + (x - \bar x_{\text{old}})(x - \bar x_{\text{new}}) n=na+nb,xˉ=xˉa+δnbn,M2=M2,a+M2,b+δ2nanbn,σ=M2/nn = n_a + n_b,\quad \bar x = \bar x_a + \delta \frac{n_b}{n},\quad M_2 = M_{2,a} + M_{2,b} + \delta^2 \frac{n_a n_b}{n},\quad \sigma = \sqrt{M_2 / n}
Expected output
2024-05-01 RunningStats(n=144, mean=22.060, std=1.825)
2024-05-14 RunningStats(n=143, mean=22.017, std=1.871)
14 days -> RunningStats(n=2010, mean=22.051, std=1.967)
True True
Starter
class RunningStats:
def __init__(self) -> None:
self.n = 0
self.mean = 0.0
self._m2 = 0.0 # sum of squared distances from the mean
# TODO: std (property), __repr__, __len__
# TODO: add(value): Welford's update, return self
# TODO: __add__(other): merge into a new RunningStats; __radd__ for sum()
daily: dict[str, RunningStats] = {}
values = [] # only for the final check
with open("data/sensors.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["sensor_id"] == "S1" and row["temperature_c"]:
pass # TODO: add the value to the RunningStats of its day (timestamp[:10])
# TODO: print two daily results, the merged result and the checks
Hint 1

add() changes self and then returns self, so calls can chain: stats.add(1.0).add(2.0).

Hint 2

daily.setdefault(day, RunningStats()) returns the stats of the day and creates them on the first value. Call .add(value) on the result.

Hint 3

In __add__, handle an empty side first: if one part has n == 0, the result is a copy of the other part. That also avoids a division by zero.

Solution
class RunningStats:
"""Count, mean and population std in one pass; mergeable with +."""
def __init__(self) -> None:
self.n = 0
self.mean = 0.0
self._m2 = 0.0 # sum of squared distances from the mean
@property
def std(self) -> float:
return math.sqrt(self._m2 / self.n) if self.n else 0.0
def __repr__(self) -> str:
return f"RunningStats(n={self.n}, mean={self.mean:.3f}, std={self.std:.3f})"
def __len__(self) -> int:
return self.n
def add(self, value: float) -> Self:
"""Add one value in place (Welford's update)."""
self.n += 1
delta = value - self.mean
self.mean += delta / self.n
self._m2 += delta * (value - self.mean) # old and new mean
return self
def __add__(self, other: object) -> "RunningStats":
if not isinstance(other, RunningStats):
return NotImplemented
result = RunningStats()
result.n = self.n + other.n
if self.n == 0 or other.n == 0:
source = other if self.n == 0 else self
result.mean, result._m2 = source.mean, source._m2
return result
delta = other.mean - self.mean
result.mean = self.mean + delta * other.n / result.n
result._m2 = self._m2 + other._m2 + delta**2 * self.n * other.n / result.n
return result
def __radd__(self, other: object) -> "RunningStats":
return self if other == 0 else NotImplemented
daily: dict[str, RunningStats] = {}
values = [] # only for the final check
with open("data/sensors.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
if row["sensor_id"] == "S1" and row["temperature_c"]:
value = float(row["temperature_c"])
day = row["timestamp"][:10]
daily.setdefault(day, RunningStats()).add(value)
values.append(value)
days = sorted(daily)
print(days[0], daily[days[0]])
print(days[-1], daily[days[-1]])
total = sum(daily.values())
print(len(daily), "days ->", total)
print(math.isclose(total.mean, statistics.fmean(values)),
math.isclose(total.std, statistics.pstdev(values)))
assert len(total) == len(values)
assert math.isclose((daily[days[0]] + RunningStats()).std, daily[days[0]].std)
Output
2024-05-01 RunningStats(n=144, mean=22.060, std=1.825)
2024-05-14 RunningStats(n=143, mean=22.017, std=1.871)
14 days -> RunningStats(n=2010, mean=22.051, std=1.967)
True True

How it works:

  1. daily.setdefault(day, RunningStats()) gives the stats of the day, and .add(value) updates the count, the mean and M2M_2 in place.
  2. Welford’s update uses the distance to the old mean and to the new mean. It avoids the large, nearly equal sums of the textbook formula ∑x2−nxˉ2\sum x^2 - n\bar x^2, which lose precision.
  3. __add__ merges two parts with the formula of Chan and others. It returns a new object, so the daily results stay unchanged. The empty case returns a copy and avoids a division by zero.
  4. sum(daily.values()) uses __radd__ for the start value 0, then __add__. The merged mean and std match the one-pass statistics results.
  5. Why add() and not stats += value? + merges two accumulators. If += added a number, stats += 5.0 would work but stats + 5.0 would raise TypeError: one operator with two meanings, the surprise that the lesson warns against. A named method says what it does. (+= on a RunningStats still works through __add__: a += b merges b into a new object and rebinds a.)

Alternative: with pandas, df.groupby(df["timestamp"].str[:10])["temperature_c"].agg(["count", "mean", "std"]) gives the daily numbers (with ddof=1 by default, module 29 explains the difference). The mergeable form matters when the data never fits in one process, as in Spark or Dask.