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:
- Read the task and the expected output.
- Copy the setup block below and the starter code into a script (for example
exercise.py). Replace each to-do comment with your code. - Run the script from your project folder with
python exercise.py. Compare your output with the expected output. - Stuck? Open one hint at a time. Open the solution only after a real attempt.
Each solution ends with assert checks. 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 csvimport inspectimport mathimport reimport statisticsimport unicodedatafrom collections import Counterfrom collections.abc import Callable, Iterable, Iteratorfrom functools import total_orderingfrom itertools import islice, productfrom typing import Any, SelfWarm-up
Section titled “Warm-up”M20-W01 · Give a sensor a repr and a str
Section titled “M20-W01 · Give a sensor a repr and a str”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.
S1 (server room)Sensor('S1', 'server room')[Sensor('S1', 'server room')]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 objectS1 (server room)Sensor('S1', 'server room')[Sensor('S1', 'server room')]How it works:
print(sensor)callsstr(sensor), which runs__str__.repr(sensor)runs__repr__. The!rflag callsrepr()on each string, which adds the quotes.- A list shows the repr of each item, never the str.
- 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”Predict the output: read the code and write down, line by line, what it prints. Then run it.
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)P002 at 249.00 USDProduct('P002', 249.0)[Product('P002', 249.0)]p=Product('P002', 249.0){'best seller': Product('P002', 249.0)}TrueHow it works:
print(p)uses__str__: the price shows with 2 decimals.!rforces the repr. Inside the repr,{self.price!r}shows249.0, the plain float repr, not the formatted price.- A list and a dict show the repr of each value.
{p=}is the debugging form: it showsp=and the repr.format(p)with no spec callsobject.__format__, which returnsstr(p).
M20-W03 · Count a batch with len
Section titled “M20-W03 · Count a batch with len”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__.
5Falsenothing to processclass 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) == 0assert batch and not empty5Falsenothing to processHow it works:
len(batch)runsBatch.__len__, which returns the length of the list.bool(empty)finds no__bool__, so it calls__len__. The result 0 makes the batch falsy.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”.
M20-W04 · Fix the unhashable store key
Section titled “M20-W04 · Fix the unhashable store key”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__.
5 lines, 4 storesStoreKey('S04', 'South')StoreKey('S05', 'South')StoreKey('S10', 'West')StoreKey('S11', 'West')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) == 4assert hash(StoreKey("S11", "West")) == hash(lines[0])5 lines, 4 storesStoreKey('S04', 'South')StoreKey('S05', 'South')StoreKey('S10', 'West')StoreKey('S11', 'West')How it works:
- Defining
__eq__without__hash__setStoreKey.__hash__toNone, soset()refused the objects. - 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. - The set keeps one
S11key, 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.
M20-W05 · Check valid ages with contains
Section titled “M20-W05 · Check valid ages with contains”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.
ValidRange(18, 80)[17, 81, '45', None]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 validHint 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 validassert "45" not in validValidRange(18, 80)[17, 81, '45', None]How it works:
age in validcallsvalid.__contains__(age).not incalls the same method and inverts the result.isinstance()rejects the string"45"andNonebefore any comparison runs.andstops early, so the comparison never sees them.- 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.
M20-W06 · A callable unit converter
Section titled “M20-W06 · A callable unit converter”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.
LinearUnit(1.8, 32)[67.1, 69.26, 68.18]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 readingsHint 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)LinearUnit(1.8, 32)[67.1, 69.26, 68.18]How it works:
to_fahrenheit(value)runsLinearUnit.__call__. The object keeps its two settings in attributes.map()accepts any callable, so the object works where a function is expected.- 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”Predict the output: write down, line by line, what the code prints. Each special method prints its own name when Python calls it.
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"Left.__add__Right.__radd__handled by RightRight.__radd__handled by RightTypeError: unsupported operand type(s) for +: 'Right' and 'int'Right.__radd__How it works:
Left() + Right():Left.__add__runs and returnsNotImplemented, so Python triesRight.__radd__, which handles it.1 + Right():int.__add__does not knowRightand returnsNotImplemented. Python triesRight.__radd__. This is the path thatsum()takes.Right() + 1:Righthas no__add__, andint.__radd__does not knowRight. Both sides decline, so Python raisesTypeError.- The assert line calls
__radd__once more, soRight.__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”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.
[Discount(0.05), Discount(0.1)]2 of 6 lines discountedclass 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[Discount(0.05), Discount(0.1)]2 of 6 lines discountedHow it works:
if dcallsbool(d), which runsDiscount.__bool__.self.rate != 0is a comparison, so it returns a realbool. Returningself.rateitself would raiseTypeError: __bool__ should return bool, returned float.- 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”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.
['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@total_orderingclass 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_orderingclass 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['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') TrueHow it works:
__init__splits"1.10.0"into the tuple(1, 10, 0)of integers.__lt__compares the tuples. Tuples compare their first elements, then the second ones, and so on, so(1, 10, 0) > (1, 9, 3).@total_orderingbuilds>=from__lt__and__eq__.sorted()andmax()need only<.- 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()”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.
floats: 2856.1099999999997money: 2,856.11 USD Money(285611)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 sumHint 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)floats: 2856.1099999999997money: 2,856.11 USD Money(285611)How it works:
Money.from_textturns"66.49"into 6,649 cents once.round()removes the tiny float error of66.49 * 100.sum()computes0 + m1.intdeclines, andMoney.__radd__returnsm1. After that, every step isMoney + Money, which__add__handles.- The float sum shows
2856.1099999999997because 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.
M20-C03 · Fix the endless radd
Section titled “M20-C03 · Fix the endless radd”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__.
Units(14)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 == 14Units(14)How it works:
sum()evaluates0 + units[0].int.__add__returnsNotImplemented, so Python callsunits[0].__radd__(0).- The old
__radd__evaluated0 + self: the very same expression. Python called__radd__again, and again, until the call stack limit raisedRecursionError. - 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”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.
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²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_sqmHint 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]) == 3assert stores["store_id"][0] == stores[0]["store_id"] == "S01"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:
stores["city"]is astrkey, so__getitem__returns that column list.stores[-1]andstores[0]areintkeys. The method picks the same position in every column and returns a dict. Negative positions work because lists understand them.stores[3:6]passes a slice object. Slicing every column keeps the rows aligned, andtype(self)(...)returns aTable, so["city"]works on the result.__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”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.
H0001 1.906H0003 1.136H0004 0.5[1.84, 3.0, 2.75] 16.24def 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 operatorsHint 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)H0001 1.906H0003 1.136H0004 0.5[1.84, 3.0, 2.75] 16.24How it works:
- Each helper function became a special method. The call sites now read like the math:
abs(features - listing)is , the distance. 0.5 * (a + b)needs__rmul__, because the float is on the left.__rmul__ = __mul__reuses the method.zip(..., strict=True)raisesValueErrorfor vectors of different lengths, which the old helpers silently cut short.- 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.
M20-C06 · A re-iterable sensor series
Section titled “M20-C06 · A re-iterable sensor series”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.
SensorSeries('data/sensors.csv', 'S3', column='temperature_c')2010 23.53 41.66class 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 againassert 0 < n <= 2016SensorSeries('data/sensors.csv', 'S3', column='temperature_c')2010 23.53 41.66How it works:
__iter__is a generator method. Everyfor,sum()ormax()callsiter(s3), which starts a new generator that opens the file from the top.- The generator filters the rows of S3 and skips blank cells, then converts each value to
float. __len__counts with one full pass. It is correct but costs a file read, so the code stores the result inninstead of callinglen()twice.- 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”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 driftprint(r in seen)print(len(seen), any(x is r for x in seen))False1 TrueExplain 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:
True False1 Reading('S3', 22.55)AttributeError: property 'celsius' of 'Reading' object has no setterclass 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 driftprint(r in seen)print(len(seen), any(x is r for x in seen))# TODO: explain the output, then make Reading immutableHint 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.55except AttributeError as error: print("AttributeError:", error)assert r in seen and fixed not in seenTrue False1 Reading('S3', 22.55)AttributeError: property 'celsius' of 'Reading' object has no setterHow it works:
- In the original code,
seen = {r}putrin the bucket forhash(("S3", 22.9)). - The correction changed
celsiusto 22.55, sohash(r)changed too.r in seenlooked in the bucket for("S3", 22.55), found nothing and printedFalse. - The set still holds the object:
len(seen)is 1, andany(x is r ...)finds it by identity. The object sits in a bucket that no lookup reaches any more. - 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”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.
inside: 0.3 3after: 0.5 Falseerror: report failed | max_discount = 0.2import 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 blockHint 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 == originalinside: 0.3 3after: 0.5 Falseerror: report failed | max_discount = 0.2How it works:
__enter__saves the current value of each key that will change, or the_MISSINGmarker when the key is new. Then it applies the changes and returns the dict foras.__exit__runs after the block in every case. It puts old values back and deletes keys that did not exist.- In the second block, the
RuntimeErrorpasses through__exit__, which restoresmax_discount, and returnsNone, so the error reaches theexceptclause. _MISSINGis a freshobject(), so it cannot be confused with a real setting, not evenNone.
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”Choose a method and justify it. A team needs a FeatureStore class for model inputs. The requirements:
len(store)gives the number of features.store["age"]gives the values of a feature; an unknown name raisesKeyError."age" in storemust be fast (no loop over the features).for name in storegives the feature names in the order they were added.print(store)showsFeatureStore(['age', 'tenure_months']).- 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.
FeatureStore(['age', 'tenure_months']) 2[18.0, 23.0, 24.0, 38.0, 41.0]True False ['age', 'tenure_months']Noneclass 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 == storeFeatureStore(['age', 'tenure_months']) 2[18.0, 23.0, 24.0, 38.0, 41.0]True False ['age', 'tenure_months']NoneHow it works:
__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]raisesKeyErrorfor an unknown name.__contains__is a deliberate choice. Without it,inwould fall back to__iter__and scan the names one by one. The dict lookup is a hash lookup, which takes constant time.__eq__covers requirement 6 and has the side effect: Python sets__hash__toNone, so stores are unhashable. That is correct, becauseadd()changes a store.__iter__yields names, and__contains__tests names, soforandinagree, 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”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.
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__lt(0.815, 0.845)Truelt(0.845, 0.815)FalseeqTrueTypeError: '<=' not supported between instances of 'Score' and 'Score'How it works:
a < bcallsa.__lt__(b)directly.a > b:Scoreinheritsobject.__gt__, which returnsNotImplemented. Python tries the reflectionb.__lt__(a), so it printslt(0.845, 0.815)and the answerFalse.a != b: the default__ne__calls__eq__(which printseq) and inverts itsFalse.a <= b:__le__and its reflectionb.__ge__(a)both returnNotImplemented, so Python raisesTypeError.@total_orderingwould add both.- The assert confirms that
Scoreonly has the__le__inherited fromobject.
M20-C11 · Fix an eq that crashes on None
Section titled “M20-C11 · Fix an eq that crashes on None”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.
TrueFalse False1class 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: E711print(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: E711print(refunds.count(None))assert Money(0) in refunds and (Money(0) != None) # noqa: E711TrueFalse False1How it works:
Money(0) in refundscompares with each item in turn. The old__eq__readother.centsfromNoneand crashed.- The fixed
__eq__returnsNotImplementedforNoneand for the float14.99. Python tries the reflected comparison, which also declines, and falls back to identity:False. refunds.count(None)comparesNonewith each item. ForNone == Money(...),Nonedeclines and Python asksMoney.__eq__, which must not crash either.- The
# noqa: E711comments silence the linter rule “compare withNoneusingis”, because this test compares withNoneon 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”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.
Compose(nfc, strip, collapse_spaces, title) 4José GarcíaZoë O'BrienFrançois DupontBjörk GuðmundsdóttirAnna-Lena MüllerSøren KierkegaardMei ChenJosé Garcíadef 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 namesHint 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 matchCompose(nfc, strip, collapse_spaces, title) 4José GarcíaZoë O'BrienFrançois DupontBjörk GuðmundsdóttirAnna-Lena MüllerSøren KierkegaardMei ChenJosé GarcíaHow it works:
Composestores the steps in a tuple.__call__passes the value through each step in order.str.stripandstr.titleare unbound methods:str.title("ab")is the same as"ab".title(), so they work as one-argument functions.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 thenfcstep,str.title()treats the combining accent as a word break and returnsGarcíA.__len__makesComposetruthy 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”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.
KNNClassifier()KNNClassifier(n_neighbors=15)KNNClassifier(n_neighbors=3, weights='distance')StandardScaler(with_std=False)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",}KNNClassifier()KNNClassifier(n_neighbors=15)KNNClassifier(n_neighbors=3, weights='distance')StandardScaler(with_std=False)How it works:
inspect.signature(cls.__init__)describes the parameters of__init__. EachParameterhas a.default.- The repr keeps only the parameters whose current value differs from the default.
KNNClassifier(n_neighbors=5)prints asKNNClassifier(): the output is shorter, and it still rebuilds an equal model, because the defaults fill in the rest.- 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.
Challenge
Section titled “Challenge”M20-X01 · A confusion matrix you can index and add
Section titled “M20-X01 · A confusion matrix you can index and add”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:
- builds itself from
y_trueandy_predwith a class methodfrom_predictions; - returns one count for a tuple key:
cm[1, 0]is the number of churners predicted as “stay”; - supports
len(cm)(the number of samples),==,+andsum()over folds; - has a short repr and a
__str__that prints a 2 × 2 table; - has
accuracy,precisionandrecallfor the label 1.
Print the size and the true positives of each fold, then the total table and the three scores.
fold 1: 1000 rows, true positives = 0fold 2: 1000 rows, true positives = 0fold 3: 1000 rows, true positives = 0fold 4: 1000 rows, true positives = 1fold 5: 1000 rows, true positives = 62ConfusionMatrix(n=5000, labels=(0, 1))actual \ predicted 0 1 0 4010 27 1 900 63accuracy 0.815 precision 0.700 recall 0.065class 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 scoresHint 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 = cm[1, 1] / (cm[1, 1] + cm[0, 1]). Recall is = 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)fold 1: 1000 rows, true positives = 0fold 2: 1000 rows, true positives = 0fold 3: 1000 rows, true positives = 0fold 4: 1000 rows, true positives = 1fold 5: 1000 rows, true positives = 62ConfusionMatrix(n=5000, labels=(0, 1))actual \ predicted 0 1 0 4010 27 1 900 63accuracy 0.815 precision 0.700 recall 0.065How it works:
from_predictionscounts the(actual, predicted)pairs withCounterand hands them to__init__, which fills every pair of labels, with 0 for pairs that never occur.cm[1, 1]passes the tuple(1, 1)to__getitem__. A dict with tuple keys does the lookup.sum(folds)starts with0 + 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.- 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.
- 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”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:
- builds itself from texts with a class method
from_texts(lowercase, words matched by the regex[a-z']+); - returns the count of a word with
table["great"], and 0 for a word it never saw; - supports
len()(the number of distinct words),in,==,+andsum(); - iterates over the words from the most to the least frequent, with ties in alphabetical order;
- 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".
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 Falseclass 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 passHint 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)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 FalseHow it works:
from_textslowercases each text and extracts its words with the regex, then counts them in aCounter.__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.sum(chunks)merges the three tables.Counter + Counteradds the counts word by word. The first assert proves that merging chunks gives the same table as one pass over all texts.__iter__sorts by count, then by word, soislice(table, 5)gives the top five.- “warranty” never appears in the review texts, so its count is 0 and
inisFalse. The table never stores the 0, solen(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”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:
- Arithmetic
+,-,*,/works element by element with anotherColumnof the same length, and with a number on either side (price / 1000,1 / sqft). - Comparisons
>,<,>=,<=and==return aColumnofboolvalues: a mask. col[mask]keeps the values where the mask isTrue;col[i]andcol[a:b]work as usual.if col:raisesValueError, because the truth of a whole column is ambiguous.len(), iteration, a short repr and amean()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.
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,600Column('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()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 housesHint 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 / sqftprint(per_sqft)big = sqft > 2000print(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]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,600Column('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:
_applyis the single place that knows the rules: aColumnpairs values, a number is repeated, anything else returnsNotImplemented.price / sqftcalls__truediv__with aColumn. The result has no name, because the two names differ (pandas uses the same rule).1000 / sqftstarts withint.__truediv__, which declines, so Python callssqft.__rtruediv__(1000), which computes1000 / valuefor each value.sqft > 2000calls__gt__and returns a mask.price[big]passes the mask to__getitem__, which keeps the matching prices.~bigcalls__invert__.__eq__returns aColumn, not abool, so the class sets__hash__ = Noneexplicitly. Python would do it anyway, because the class defines__eq__; writing it shows the intent.__bool__raises, soif big:fails loudly instead of guessing. pandas and NumPy raise the same kind ofValueError.
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”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:
- takes a dict such as
{"scaler__with_std": [True, False], "knn__n_neighbors": [1, 5, 15, 25, 45]}; - gives
len(grid)as the product of the list lengths; - computes
grid[i]directly fromi(negative indexes too,IndexErrorpast the end) andgrid[a:b]as a list; - iterates in the same order as
itertools.product, the last key changing fastest; - answers
params in gridwithout 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.
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 False1,000,000,000 {'a': 123, 'b': 456, 'c': 789}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 itHint 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]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 False1,000,000,000 {'a': 123, 'b': 456, 'c': 789}How it works:
__len__multiplies the list lengths: 2 × 2 × 5 = 20.__getitem__peels off one position per key withdivmod, 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, sohuge[123_456_789]is instant althoughhugehas a billion combinations.- A slice becomes the exact positions through
range(len(self))[key], which handles negative and stepped slices for free. __iter__usesitertools.product, which produces the same order. The first assert proves that iteration and indexing agree.__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”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:
- adds one value with a named method,
stats.add(value), using Welford’s algorithm from module 18, and returnsself; - merges two results with
a + binto a new object, and supportssum(). Use+only for merging: adding one number is a different operation, so it gets a name; - has
len()(the count),mean,stdand a repr.
Check the merged result against statistics.fmean() and statistics.pstdev() on all values.
The update rules, for a new value and for two parts and with :
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 Trueclass 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 checkwith 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 checksHint 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 checkwith 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)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 TrueHow it works:
daily.setdefault(day, RunningStats())gives the stats of the day, and.add(value)updates the count, the mean and in place.- 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 , which lose precision.
__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.sum(daily.values())uses__radd__for the start value 0, then__add__. The merged mean and std match the one-passstatisticsresults.- Why
add()and notstats += value?+merges two accumulators. If+=added a number,stats += 5.0would work butstats + 5.0would raiseTypeError: one operator with two meanings, the surprise that the lesson warns against. A named method says what it does. (+=on aRunningStatsstill works through__add__:a += bmergesbinto a new object and rebindsa.)
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.