Skip to content

18. Classes and objects — Exercises

These exercises practice every idea of the Classes and objects lesson. They model the course datasets as objects: products, stores, houses, customers, sensor readings, sales lines and reviews. Some exercises leave data science: a game entity, an HTTP request and a model registry.

How to work:

  1. Read the task and the expected output.
  2. Copy the starter code into a script (for example exercise.py) in your project folder and replace each to-do comment with your code.
  3. Run the script 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. Each solution is self-contained: it has all its imports and classes, so you can run it alone.

Warm-up

Write a class Product for rows of data/products.csv. __init__ takes product_id, name, unit_cost and unit_price. Add a method margin() that returns unit_price - unit_cost rounded to 2 decimals, and a method margin_rate() that returns the margin divided by the price, rounded to 3 decimals. Create P001 (Wireless Earbuds, cost 31.5, price 79.99) and P002 (Noise-Cancelling Headphones, cost 104.0, price 249.0) and print one line for each.

Expected output
P001 Wireless Earbuds: margin 48.49 USD (60.6%)
P002 Noise-Cancelling Headphones: margin 145.0 USD (58.2%)
Starter
class Product:
def __init__(self, product_id: str, name: str, unit_cost: float, unit_price: float):
# TODO: store the four values as instance attributes
...
# TODO: margin() and margin_rate()
earbuds = Product("P001", "Wireless Earbuds", 31.5, 79.99)
headphones = Product("P002", "Noise-Cancelling Headphones", 104.0, 249.0)
# TODO: print "P001 Wireless Earbuds: margin 48.49 USD (60.6%)" and the same for P002
Hint 1

Each line of __init__ has the form self.name = name. Inside a method, read the values back with self.unit_price.

Hint 2

margin_rate() can call the other method: self.margin() / self.unit_price. In the f-string, :.1% shows a fraction as a percentage with one decimal.

Solution
class Product:
def __init__(self, product_id: str, name: str, unit_cost: float, unit_price: float):
self.product_id = product_id
self.name = name
self.unit_cost = unit_cost
self.unit_price = unit_price
def margin(self) -> float:
return round(self.unit_price - self.unit_cost, 2)
def margin_rate(self) -> float:
return round(self.margin() / self.unit_price, 3)
earbuds = Product("P001", "Wireless Earbuds", 31.5, 79.99)
headphones = Product("P002", "Noise-Cancelling Headphones", 104.0, 249.0)
for p in (earbuds, headphones):
print(f"{p.product_id} {p.name}: margin {p.margin()} USD ({p.margin_rate():.1%})")
assert earbuds.margin() == 48.49
assert headphones.margin_rate() == 0.582
assert vars(earbuds)["unit_cost"] == 31.5
Output
P001 Wireless Earbuds: margin 48.49 USD (60.6%)
P002 Noise-Cancelling Headphones: margin 145.0 USD (58.2%)

How it works:

  1. __init__ stores the four arguments on self, so each Product instance has its own four attributes.
  2. margin() reads two attributes of the instance it is called on. For earbuds, self is earbuds.
  3. margin_rate() calls self.margin(), so the margin formula exists in one place only.
  4. The loop treats both objects the same way, because they share the methods of the class.

Alternative: margin could be a property (@property def margin(self)), so callers write p.margin without parentheses. Use a property for a cheap value that reads like data; use a method when the call does real work or takes arguments.

M18-W02 · Predict the output: class and instance attributes

Section titled “M18-W02 · Predict the output: class and instance attributes”
Warm-up

Predict the output: write down what each print shows. Then run the code and compare.

Acceptance criteria:

  • Write your prediction for all four lines before you run the code.
  • Run the code. Your prediction matches the Output in the solution, line by line.
  • For each line you got wrong, you can say in which namespace Python found the value.
Starter
class Store:
currency = "USD"
def __init__(self, store_id: str):
self.store_id = store_id
s1 = Store("S01")
s2 = Store("S02")
s1.currency = "EUR"
Store.currency = "CAD"
print(s1.currency, s2.currency, Store.currency)
print(vars(s1))
print(vars(s2))
del s1.currency
print(s1.currency)
# TODO: write your prediction for each print before you run it
Hint 1

s1.currency = "EUR" is an assignment through an instance. Where does it store the value?

Hint 2

del s1.currency deletes the instance attribute. After that, the lookup of s1.currency falls back to the class.

Solution
class Store:
currency = "USD"
def __init__(self, store_id: str):
self.store_id = store_id
s1 = Store("S01")
s2 = Store("S02")
s1.currency = "EUR"
Store.currency = "CAD"
print(s1.currency, s2.currency, Store.currency)
print(vars(s1))
print(vars(s2))
del s1.currency
print(s1.currency)
assert "currency" not in vars(s1)
assert s1.currency == s2.currency == "CAD"
Output
EUR CAD CAD
{'store_id': 'S01', 'currency': 'EUR'}
{'store_id': 'S02'}
CAD

How it works:

  1. s1.currency = "EUR" creates an instance attribute on s1. It shadows the class attribute for s1 only.
  2. Store.currency = "CAD" changes the class attribute. s2 has no attribute of its own, so it sees CAD. s1 still sees its own EUR.
  3. vars(s1) shows both instance attributes of s1. vars(s2) shows only store_id; currency is not stored on s2 at all.
  4. After del s1.currency, the instance attribute is gone, so s1.currency falls back to the class value, CAD.

Alternative: check where a value lives with "currency" in vars(s1). It is True only for an instance attribute, while hasattr(s1, "currency") is True in both cases.

Warm-up

Fix the bug: this class for data/stores.csv should report the revenue per square meter of a store. Store S01 (Chicago, 2,850 m²) had a revenue of 412,560.25 USD in a quarter. The call raises a TypeError. Find the two mistakes and fix them.

Expected output
S01 Chicago: 144.76 USD/m²
Starter
class StoreRecord:
def __init__(self, store_id: str, city: str, size_sqm: int):
self.store_id = store_id
self.city = city
self.size_sqm = size_sqm
def revenue_per_sqm(revenue: float) -> float:
return round(revenue / size_sqm, 2)
chicago = StoreRecord("S01", "Chicago", 2850)
rate = chicago.revenue_per_sqm(412_560.25)
print(f"{chicago.store_id} {chicago.city}: {rate} USD/m²")
# TODO: fix the method so that the call works
Hint 1

Run the code and read the last line of the traceback. How many arguments does Python say it passed?

Hint 2

After you add the first parameter, the next run raises a NameError. Inside a method, how do you reach an attribute of the instance?

Solution
class StoreRecord:
def __init__(self, store_id: str, city: str, size_sqm: int):
self.store_id = store_id
self.city = city
self.size_sqm = size_sqm
def revenue_per_sqm(self, revenue: float) -> float:
return round(revenue / self.size_sqm, 2)
chicago = StoreRecord("S01", "Chicago", 2850)
rate = chicago.revenue_per_sqm(412_560.25)
print(f"{chicago.store_id} {chicago.city}: {rate} USD/m²")
assert chicago.revenue_per_sqm(2850) == 1.0
assert StoreRecord.revenue_per_sqm(chicago, 5700) == 2.0
Output
S01 Chicago: 144.76 USD/m²

How it works:

  1. Bug 1: the method had no self. Python passes the instance plus 412_560.25, which is 2 arguments for 1 parameter: TypeError: StoreRecord.revenue_per_sqm() takes 1 positional argument but 2 were given.
  2. Bug 2: size_sqm alone is a local or global name, and neither exists. The value lives on the instance: self.size_sqm.
  3. The second assert shows what chicago.revenue_per_sqm(5700) really does: it calls the function in the class with chicago as the first argument.

Alternative: if the method is only a formula over an attribute and an argument, it is fine as a method. If you need the same formula for raw numbers too, write a module function revenue_per_sqm(revenue, size_sqm) and call it from the method.

Warm-up

Write a class House with house_id, sqft and price. Add a read-only property price_per_sqft that returns the price divided by the area, rounded to 2 decimals. Use house H0001 from data/houses.csv (2,420 sqft, 1,097,500 USD). Print the value, change the price to 1,150,000 and print it again. Then show that h.price_per_sqft = 0 fails, by catching the AttributeError and printing its message.

Expected output
H0001 453.51
H0001 475.21
error: property 'price_per_sqft' of 'House' object has no setter
Starter
class House:
def __init__(self, house_id: str, sqft: int, price: int):
self.house_id = house_id
self.sqft = sqft
self.price = price
# TODO: a property price_per_sqft
h = House("H0001", 2420, 1_097_500)
# TODO: print the property, change the price, print again
# TODO: try to assign the property and print the error message
Hint 1

Write a method price_per_sqft(self) and put @property on the line above it. Read it without parentheses: h.price_per_sqft.

Hint 2

Put the assignment in try: and catch AttributeError as exc. print(exc) shows the message.

Solution
class House:
def __init__(self, house_id: str, sqft: int, price: int):
self.house_id = house_id
self.sqft = sqft
self.price = price
@property
def price_per_sqft(self) -> float:
return round(self.price / self.sqft, 2)
h = House("H0001", 2420, 1_097_500)
print(h.house_id, h.price_per_sqft)
h.price = 1_150_000
print(h.house_id, h.price_per_sqft)
try:
h.price_per_sqft = 0
except AttributeError as exc:
print("error:", exc)
assert h.price_per_sqft == round(1_150_000 / 2420, 2)
assert "price_per_sqft" not in vars(h)
Output
H0001 453.51
H0001 475.21
error: property 'price_per_sqft' of 'House' object has no setter

How it works:

  1. @property turns the method into a property on the class. h.price_per_sqft runs the method and returns its value.
  2. The value is computed on every read, so it follows the price change at once.
  3. The property has no setter, so an assignment raises an AttributeError that names the property and the class.
  4. The second assert shows that nothing is stored on the instance under that name.

Alternative: a method price_per_sqft() gives the same numbers. The property reads like a column of the data, which is how analysts think of it.

M18-W05 · An alternative constructor from a CSV line

Section titled “M18-W05 · An alternative constructor from a CSV line”
Warm-up

Write a class Store with store_id, city, region, size_sqm (an int) and opened (a str). Add a class method from_csv_line(line) that splits one line of data/stores.csv on commas and returns a Store. Build S01 and S02 from the two lines in the starter and print them.

Expected output
S01 Chicago (North): 2850 m², opened 2009-03-14
S02 Minneapolis (North): 1950 m², opened 2012-08-01
Starter
class Store:
def __init__(
self, store_id: str, city: str, region: str, size_sqm: int, opened: str
):
self.store_id = store_id
self.city = city
self.region = region
self.size_sqm = size_sqm
self.opened = opened
# TODO: a class method from_csv_line(cls, line)
lines = [
"S01,Chicago,North,2850,2009-03-14\n",
"S02,Minneapolis,North,1950,2012-08-01\n",
]
# TODO: build one Store per line and print "S01 Chicago (North): 2850 m², opened 2009-03-14"
Hint 1

Put @classmethod above the method and name the first parameter cls. line.strip().split(",") gives a list of 5 strings.

Hint 2

Unpack the list into 5 names, convert size_sqm with int(), then return cls(store_id, city, region, int(size_sqm), opened).

Solution
from typing import Self
class Store:
def __init__(
self, store_id: str, city: str, region: str, size_sqm: int, opened: str
):
self.store_id = store_id
self.city = city
self.region = region
self.size_sqm = size_sqm
self.opened = opened
@classmethod
def from_csv_line(cls, line: str) -> Self:
store_id, city, region, size_sqm, opened = line.strip().split(",")
return cls(store_id, city, region, int(size_sqm), opened)
lines = [
"S01,Chicago,North,2850,2009-03-14\n",
"S02,Minneapolis,North,1950,2012-08-01\n",
]
stores = [Store.from_csv_line(line) for line in lines]
for s in stores:
print(f"{s.store_id} {s.city} ({s.region}): {s.size_sqm} m², opened {s.opened}")
assert isinstance(stores[0], Store)
assert stores[1].size_sqm == 1950 and isinstance(stores[1].size_sqm, int)
Output
S01 Chicago (North): 2850 m², opened 2009-03-14
S02 Minneapolis (North): 1950 m², opened 2012-08-01

How it works:

  1. Store.from_csv_line(line) passes the class as cls and the text as line.
  2. strip() removes the line break, and split(",") cuts the line into its 5 fields.
  3. cls(...) is the normal constructor call, so the object goes through __init__ with clean, typed values.
  4. Self says that the method returns an instance of the class it is called on.

Alternative: for a whole file, read it with csv.DictReader and write from_csv_row(cls, row: dict[str, str]), which reads the fields by name. That is safer when the column order can change, and it handles quoted commas.

M18-W06 · Static methods for unit conversion

Section titled “M18-W06 · Static methods for unit conversion”
Warm-up

Write a class Temperature that groups two static methods: c_to_f(celsius) and f_to_c(fahrenheit), both rounded to 2 decimals. Convert the S1 reading 20.21 °C to °F, convert 98.6 °F to °C, and show that the round trip gives back 20.21. Call one method through the class and one through an instance, to see that both work.

Expected output
S1: 68.38 °F
Body temperature: 37.0 °C
Round trip: 20.21
Starter
class Temperature:
# TODO: two static methods c_to_f and f_to_c
...
# TODO: print the three results
Hint 1

Put @staticmethod above each def. A static method has no self or cls parameter: def c_to_f(celsius: float) -> float:.

Hint 2

°F = °C × 9 / 5 + 32 and °C = (°F − 32) × 5 / 9. Call them as Temperature.c_to_f(20.21) or Temperature().f_to_c(98.6).

Solution
class Temperature:
@staticmethod
def c_to_f(celsius: float) -> float:
return round(celsius * 9 / 5 + 32, 2)
@staticmethod
def f_to_c(fahrenheit: float) -> float:
return round((fahrenheit - 32) * 5 / 9, 2)
s1_f = Temperature.c_to_f(20.21)
print("S1:", s1_f, "°F")
print("Body temperature:", Temperature().f_to_c(98.6), "°C")
print("Round trip:", Temperature.f_to_c(s1_f))
assert Temperature.c_to_f(100) == 212.0
assert Temperature.f_to_c(Temperature.c_to_f(20.21)) == 20.21
Output
S1: 68.38 °F
Body temperature: 37.0 °C
Round trip: 20.21

How it works:

  1. @staticmethod stops Python from passing the instance or the class. The methods are plain functions stored in the class namespace.
  2. Temperature.c_to_f(20.21) and Temperature().f_to_c(98.6) both work. Through an instance, Python still passes no self.
  3. The round trip gives 20.21 back, because 68.38 °F converts to 20.2111… °C, which rounds to 20.21.

Alternative: two module-level functions c_to_f and f_to_c in a module units.py do the same job, and many projects prefer them: from units import c_to_f. A class of only static methods is mainly a way to group names; a module does that too.

M18-W07 · Predict the output: name mangling

Section titled “M18-W07 · Predict the output: name mangling”
Warm-up

Predict the output: an API client keeps an internal note and a secret key. Write down what each print shows. Then run the code and compare.

Acceptance criteria:

  • Write your prediction for all four lines before you run the code.
  • Run the code. Your prediction matches the Output in the solution, line by line.
  • You can explain why hasattr(client, "__key") and hasattr(client, "_ApiClient__key") differ.
Starter
class ApiClient:
def __init__(self, key: str):
self._note = "rate limit 60/min"
self.__key = key
def masked_key(self) -> str:
return self.__key[:4] + "****"
client = ApiClient("sk-1234567890")
print(sorted(vars(client)))
print(client.masked_key())
print(hasattr(client, "__key"), hasattr(client, "_ApiClient__key"))
print(client._note)
# TODO: write your prediction for each print before you run it
Hint 1

Inside the class body, __key is renamed. What is the new name, for a class called ApiClient?

Hint 2

hasattr takes the name as a string. Strings are not renamed. One underscore (_note) is never renamed.

Solution
class ApiClient:
def __init__(self, key: str):
self._note = "rate limit 60/min"
self.__key = key
def masked_key(self) -> str:
return self.__key[:4] + "****"
client = ApiClient("sk-1234567890")
print(sorted(vars(client)))
print(client.masked_key())
print(hasattr(client, "__key"), hasattr(client, "_ApiClient__key"))
print(client._note)
assert "_ApiClient__key" in vars(client)
assert client._ApiClient__key == "sk-1234567890"
Output
['_ApiClient__key', '_note']
sk-1****
False True
rate limit 60/min

How it works:

  1. Inside the class, self.__key is rewritten to self._ApiClient__key, in __init__ and in masked_key. So the method finds the value.
  2. sorted(vars(client)) sorts the attribute names. _ApiClient__key comes before _note, because A sorts before n.
  3. hasattr(client, "__key") looks for the literal name __key, which does not exist. The mangled name does.
  4. _note has one underscore. It is internal by convention, but Python does not rename it, and the outside code can read it.

Alternative: never rely on mangling to protect a secret. The key is still readable as client._ApiClient__key. Real code keeps secrets out of objects that get printed or logged, and reads them from environment variables (module 16).

M18-W08 · Fix the bug: the counter that never counts

Section titled “M18-W08 · Fix the bug: the counter that never counts”
Warm-up

Fix the bug: every Forecast object should get an id from a shared counter, and Forecast.created should count the objects. After three forecasts, the class counter still says 0, and every forecast gets id 1.

Expected output
1 S01 7
2 S02 7
3 S01 28
created: 3
Starter
class Forecast:
created = 0
def __init__(self, store_id: str, horizon_days: int):
self.store_id = store_id
self.horizon_days = horizon_days
self.created += 1
self.forecast_id = self.created
forecasts = [Forecast("S01", 7), Forecast("S02", 7), Forecast("S01", 28)]
for f in forecasts:
print(f.forecast_id, f.store_id, f.horizon_days)
print("created:", Forecast.created)
# TODO: fix __init__ so that the ids are 1, 2, 3 and Forecast.created is 3
Hint 1

Print vars(forecasts[0]). Which attribute did self.created += 1 create?

Hint 2

Change the counter through the class, not through self.

Solution
class Forecast:
created = 0
def __init__(self, store_id: str, horizon_days: int):
self.store_id = store_id
self.horizon_days = horizon_days
Forecast.created += 1
self.forecast_id = Forecast.created
forecasts = [Forecast("S01", 7), Forecast("S02", 7), Forecast("S01", 28)]
for f in forecasts:
print(f.forecast_id, f.store_id, f.horizon_days)
print("created:", Forecast.created)
assert [f.forecast_id for f in forecasts] == [1, 2, 3]
assert "created" not in vars(forecasts[0])
Output
1 S01 7
2 S02 7
3 S01 28
created: 3

How it works:

  1. In the bug, self.created += 1 read the class value 0 and wrote created = 1 as a new instance attribute. Each object got its own created of 1, and the class counter stayed at 0.
  2. Forecast.created += 1 changes the one value in the class namespace.
  3. self.forecast_id = Forecast.created copies the current count into an instance attribute, so each forecast keeps its own id.
  4. The second assert proves that no instance attribute created was made.

Alternative: type(self).created += 1 also works for this class; module 19 shows how it behaves with subclasses. For ids that must be unique across processes, use uuid.uuid4() instead of a counter.

M18-C01 · Customers with validated charges

Section titled “M18-C01 · Customers with validated charges”
Core

Write a class Customer for data/customers.csv with customer_id, plan and monthly_charges. Make monthly_charges a property with a setter that raises TypeError for a value that is not an int or float (reject bool) and ValueError for a value of 0 or less. Add a class method from_csv_row(row). Load all 5,000 customers, print the mean monthly charges per plan in alphabetical order, then show the two errors for -5.0 and "30.93".

Expected output
basic 2028 customers, mean 39.27 USD
premium 990 customers, mean 98.59 USD
standard 1982 customers, mean 64.04 USD
ValueError: monthly_charges must be > 0, got -5.0
TypeError: monthly_charges must be a number, got '30.93'
Starter
import csv
from typing import Self
class Customer:
def __init__(self, customer_id: str, plan: str, monthly_charges: float):
self.customer_id = customer_id
self.plan = plan
self.monthly_charges = monthly_charges # should run the setter
# TODO: the monthly_charges property and its setter (store the value in _monthly_charges)
# TODO: the class method from_csv_row
# TODO: load data/customers.csv into a list of Customer objects
# TODO: one line per plan, sorted: "basic 2028 customers, mean 39.27 USD"
# TODO: try Customer("C99999", "basic", -5.0) and Customer("C99999", "basic", "30.93")
Hint 1

The getter returns self._monthly_charges. The setter is decorated with @monthly_charges.setter and has the same name.

Hint 2

Check the type first: isinstance(value, bool) or not isinstance(value, (int, float)). Group the customers with a dict of lists, keyed by plan.

Solution
import csv
from typing import Self
class Customer:
def __init__(self, customer_id: str, plan: str, monthly_charges: float):
self.customer_id = customer_id
self.plan = plan
self.monthly_charges = monthly_charges # runs the setter
@property
def monthly_charges(self) -> float:
return self._monthly_charges
@monthly_charges.setter
def monthly_charges(self, value: float) -> None:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError(f"monthly_charges must be a number, got {value!r}")
if value <= 0:
raise ValueError(f"monthly_charges must be > 0, got {value}")
self._monthly_charges = float(value)
@classmethod
def from_csv_row(cls, row: dict[str, str]) -> Self:
return cls(row["customer_id"], row["plan"], float(row["monthly_charges"]))
with open("data/customers.csv", newline="", encoding="utf-8") as f:
customers = [Customer.from_csv_row(row) for row in csv.DictReader(f)]
by_plan: dict[str, list[float]] = {}
for c in customers:
by_plan.setdefault(c.plan, []).append(c.monthly_charges)
for plan in sorted(by_plan):
charges = by_plan[plan]
mean = sum(charges) / len(charges)
print(f"{plan:<8} {len(charges):>5} customers, mean {mean:6.2f} USD")
for bad in (-5.0, "30.93"):
try:
Customer("C99999", "basic", bad)
except (TypeError, ValueError) as exc:
print(f"{type(exc).__name__}: {exc}")
assert len(customers) == 5000
assert sum(len(v) for v in by_plan.values()) == 5000
assert all(c.monthly_charges > 0 for c in customers)
Output
basic 2028 customers, mean 39.27 USD
premium 990 customers, mean 98.59 USD
standard 1982 customers, mean 64.04 USD
ValueError: monthly_charges must be > 0, got -5.0
TypeError: monthly_charges must be a number, got '30.93'

How it works:

  1. self.monthly_charges = monthly_charges in __init__ runs the setter, so each new customer is checked, including all 5,000 from the file.
  2. The setter checks the type first, then the range. A text value such as "30.93" is a type error, even though it looks like a number.
  3. The setter stores a float in _monthly_charges, so the getter always returns the same type.
  4. setdefault(plan, []) returns the list for a plan and creates it the first time (module 04). The means rise with the plan: premium costs the most.

Alternative: pydantic (see the lesson) does the same checks with monthly_charges: float = Field(gt=0). Note one difference: pydantic converts "30.93" to 30.93 by default, while this setter rejects it. Decide which behavior your data needs.

M18-C02 · Fix the bug: selectors that share their features

Section titled “M18-C02 · Fix the bug: selectors that share their features”
Core

Fix the bug: a FeatureSelector keeps the names of the features that a model will use. Two selectors, one for a price model and one for a quality model on data/houses.csv, show each other’s features. Fix the class so that each selector has its own list, and keep max_features as a shared default that one selector can override.

Expected output
price ['sqft', 'neighborhood'] 3
quality ['condition', 'year_built'] 2
Starter
class FeatureSelector:
max_features = 3 # shared default
selected = []
def __init__(self, name: str):
self.name = name
def add(self, feature: str) -> None:
if len(self.selected) >= self.max_features:
raise ValueError(f"{self.name}: at most {self.max_features} features")
self.selected.append(feature)
price = FeatureSelector("price")
quality = FeatureSelector("quality")
price.add("sqft")
price.add("neighborhood")
quality.max_features = 2 # this selector allows only 2
quality.add("condition")
quality.add("year_built")
print(price.name, price.selected, price.max_features)
print(quality.name, quality.selected, quality.max_features)
# TODO: fix the class so that the two lists are separate
Hint 1

Run the starter. Which call fails, and why does quality already have features when it adds its first one?

Hint 2

One of the two class attributes is fine as a class attribute. The other one must become an instance attribute, created in __init__.

Solution
class FeatureSelector:
max_features = 3 # shared default; an instance can override it
def __init__(self, name: str):
self.name = name
self.selected: list[str] = [] # one list per selector
def add(self, feature: str) -> None:
if len(self.selected) >= self.max_features:
raise ValueError(f"{self.name}: at most {self.max_features} features")
self.selected.append(feature)
price = FeatureSelector("price")
quality = FeatureSelector("quality")
price.add("sqft")
price.add("neighborhood")
quality.max_features = 2 # this selector allows only 2
quality.add("condition")
quality.add("year_built")
print(price.name, price.selected, price.max_features)
print(quality.name, quality.selected, quality.max_features)
assert price.selected is not quality.selected
assert "max_features" not in vars(price) and vars(quality)["max_features"] == 2
Output
price ['sqft', 'neighborhood'] 3
quality ['condition', 'year_built'] 2

How it works:

  1. In the starter, selected is one list in the class namespace. price.add puts two names in it. When quality adds its first feature, the shared list already holds those 2 names, so add("condition") raises ValueError: quality: at most 2 features.
  2. The fix creates self.selected in __init__, so each selector gets a new, empty list.
  3. max_features is an immutable number, so it is safe as a class attribute. quality.max_features = 2 creates an instance attribute that overrides the default for quality only.
  4. The asserts check both facts: two separate lists, and one override stored on quality alone.

Alternative: pass the limit to the initializer: def __init__(self, name, max_features=3), and store self.max_features = max_features. This is clearer when most instances change the value; the class attribute is fine when most keep the default.

M18-C03 · Refactor: a revenue tracker class

Section titled “M18-C03 · Refactor: a revenue tracker class”
Core

Refactor: the procedural code in the starter sums revenue per store from the first 1,000 lines of data/sales.csv. Turn it into a class RevenueTracker with a method add(store_id, revenue), a read-only property total, and a method top(n) that returns the n best stores as (store_id, revenue) pairs with the revenue rounded to 2 decimals. The output must stay the same.

Expected output
total: 178726.0
S07 26674.22
S10 24825.31
S04 23021.06
Starter
import csv
totals = {}
def add_sale(totals, store_id, revenue):
totals[store_id] = totals.get(store_id, 0.0) + revenue
def top_stores(totals, n):
ranked = sorted(totals.items(), key=lambda kv: kv[1], reverse=True)
return [(s, round(r, 2)) for s, r in ranked[:n]]
with open("data/sales.csv", newline="", encoding="utf-8") as f:
for i, row in enumerate(csv.DictReader(f)):
if i == 1000:
break
add_sale(totals, row["store_id"], float(row["revenue"]))
print("total:", round(sum(totals.values()), 2))
for store_id, revenue in top_stores(totals, 3):
print(store_id, revenue)
# TODO: replace the dict and the two functions with a RevenueTracker class
Hint 1

The global totals dict becomes an instance attribute created in __init__. Each function becomes a method, and its totals parameter becomes self._totals.

Hint 2

total is a property that returns round(sum(self._totals.values()), 2). Read the file with itertools.islice(reader, 1000) to take the first 1,000 rows.

Solution
import csv
from itertools import islice
class RevenueTracker:
"""Revenue per store, built one sale at a time."""
def __init__(self):
self._totals: dict[str, float] = {}
def add(self, store_id: str, revenue: float) -> None:
self._totals[store_id] = self._totals.get(store_id, 0.0) + revenue
@property
def total(self) -> float:
return round(sum(self._totals.values()), 2)
def top(self, n: int) -> list[tuple[str, float]]:
ranked = sorted(self._totals.items(), key=lambda kv: kv[1], reverse=True)
return [(store_id, round(revenue, 2)) for store_id, revenue in ranked[:n]]
tracker = RevenueTracker()
with open("data/sales.csv", newline="", encoding="utf-8") as f:
for row in islice(csv.DictReader(f), 1000):
tracker.add(row["store_id"], float(row["revenue"]))
print("total:", tracker.total)
for store_id, revenue in tracker.top(3):
print(store_id, revenue)
assert len(tracker.top(3)) == 3
assert tracker.top(1)[0] == tracker.top(3)[0]
assert tracker.total >= sum(revenue for _, revenue in tracker.top(3))
Output
total: 178726.0
S07 26674.22
S10 24825.31
S04 23021.06

How it works:

  1. The state (_totals) moved into the object. It has one underscore, because callers should use add, total and top, not the dict.
  2. The global variable is gone. Two trackers, for example one per month, no longer share data by accident.
  3. total is a property: it reads like a value and is always in sync with the sales added so far.
  4. islice(reader, 1000) (module 10) stops after 1,000 rows, so the if i == 1000: break logic is gone.

Alternative: collections.Counter (module 09) already sums values per key and has most_common(n). self._totals = Counter() and self._totals[store_id] += revenue make the class shorter. The class still adds value: it hides the choice of Counter behind add and top.

M18-C04 · Validate a training configuration

Section titled “M18-C04 · Validate a training configuration”
Core

Write a class TrainConfig with three validated properties: learning_rate (a number with 0 < lr ≤ 1), epochs (an int of at least 1, not a bool) and batch_size (an int that is a power of 2, such as 32 or 64). Wrong types raise TypeError, bad values raise ValueError. Create a valid config, then print the error for each bad config in the starter.

Expected output
0.05 20 64
{'learning_rate': 0} -> ValueError: learning_rate must be in (0, 1], got 0
{'learning_rate': 1.5} -> ValueError: learning_rate must be in (0, 1], got 1.5
{'epochs': True} -> TypeError: epochs must be an int, got bool
{'epochs': 0} -> ValueError: epochs must be >= 1, got 0
{'batch_size': 48} -> ValueError: batch_size must be a power of 2, got 48
Starter
class TrainConfig:
def __init__(self, learning_rate: float = 0.01, epochs: int = 10, batch_size: int = 32):
self.learning_rate = learning_rate
self.epochs = epochs
self.batch_size = batch_size
# TODO: three properties with setters
cfg = TrainConfig(learning_rate=0.05, epochs=20, batch_size=64)
print(cfg.learning_rate, cfg.epochs, cfg.batch_size)
bad_configs = [
{"learning_rate": 0},
{"learning_rate": 1.5},
{"epochs": True},
{"epochs": 0},
{"batch_size": 48},
]
# TODO: for each bad config, print "<kwargs> -> <ErrorType>: <message>"
Hint 1

Write one getter and one setter per property, and store each value under a name with one underscore: _learning_rate, _epochs, _batch_size.

Hint 2

A positive int n is a power of 2 when n & (n - 1) == 0. The & operator compares the bits of two integers. You can also test n in {1, 2, 4, 8, 16, 32, 64, 128, 256, 512}.

Solution
class TrainConfig:
def __init__(
self, learning_rate: float = 0.01, epochs: int = 10, batch_size: int = 32
):
self.learning_rate = learning_rate
self.epochs = epochs
self.batch_size = batch_size
@staticmethod
def _check_int(name: str, value: int) -> None:
if isinstance(value, bool) or not isinstance(value, int):
raise TypeError(f"{name} must be an int, got {type(value).__name__}")
@property
def learning_rate(self) -> float:
return self._learning_rate
@learning_rate.setter
def learning_rate(self, value: float) -> None:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError(f"learning_rate must be a number, got {value!r}")
if not 0 < value <= 1:
raise ValueError(f"learning_rate must be in (0, 1], got {value}")
self._learning_rate = value
@property
def epochs(self) -> int:
return self._epochs
@epochs.setter
def epochs(self, value: int) -> None:
self._check_int("epochs", value)
if value < 1:
raise ValueError(f"epochs must be >= 1, got {value}")
self._epochs = value
@property
def batch_size(self) -> int:
return self._batch_size
@batch_size.setter
def batch_size(self, value: int) -> None:
self._check_int("batch_size", value)
if value < 1 or value & (value - 1) != 0:
raise ValueError(f"batch_size must be a power of 2, got {value}")
self._batch_size = value
cfg = TrainConfig(learning_rate=0.05, epochs=20, batch_size=64)
print(cfg.learning_rate, cfg.epochs, cfg.batch_size)
bad_configs = [
{"learning_rate": 0},
{"learning_rate": 1.5},
{"epochs": True},
{"epochs": 0},
{"batch_size": 48},
]
errors = []
for kwargs in bad_configs:
try:
TrainConfig(**kwargs)
except (TypeError, ValueError) as exc:
errors.append(type(exc).__name__)
print(f"{kwargs} -> {type(exc).__name__}: {exc}")
assert errors == ["ValueError", "ValueError", "TypeError", "ValueError", "ValueError"]
assert TrainConfig().batch_size == 32
Output
0.05 20 64
{'learning_rate': 0} -> ValueError: learning_rate must be in (0, 1], got 0
{'learning_rate': 1.5} -> ValueError: learning_rate must be in (0, 1], got 1.5
{'epochs': True} -> TypeError: epochs must be an int, got bool
{'epochs': 0} -> ValueError: epochs must be >= 1, got 0
{'batch_size': 48} -> ValueError: batch_size must be a power of 2, got 48

How it works:

  1. Each assignment in __init__ runs a setter, so a bad value fails at construction.
  2. The static method _check_int holds the type check that two setters share. It needs neither the instance nor the class.
  3. 0 < value <= 1 is a chained comparison (module 01). It rejects 0 and 1.5.
  4. 48 & 47 is not 0, because 48 (binary 110000) has two 1 bits. A power of 2 has exactly one 1 bit, so n & (n - 1) clears it and gives 0.

Alternative: with many fields like this, a dataclass with a __post_init__ check (module 21) or a pydantic model is shorter. Properties are the right tool when one value must be checked on every later assignment too.

M18-C05 · Predict the output: a game entity

Section titled “M18-C05 · Predict the output: a game entity”
Core

Predict the output: this class from a small 2D game mixes a class attribute, instance attributes, a class method, a static method and a property. Write down what each print shows. Then run the code and compare.

Acceptance criteria:

  • Write your prediction for all five lines before you run the code.
  • Run the code. Your prediction matches the Output in the solution, line by line.
  • For each line, you can name the kind of attribute or method that produced it.
Starter
from typing import Self
class Player:
max_health = 100
count = 0
def __init__(self, name: str, x: int = 0, y: int = 0):
self.name = name
self.x, self.y = x, y
self.health = self.max_health
Player.count += 1
@classmethod
def spawn_at_origin(cls, name: str) -> Self:
return cls(name)
@staticmethod
def clamp(value: int, low: int, high: int) -> int:
return max(low, min(value, high))
@property
def is_alive(self) -> bool:
return self.health > 0
def take_damage(self, amount: int) -> None:
self.health = self.clamp(self.health - amount, 0, self.max_health)
def move(self, dx: int, dy: int) -> None:
self.x, self.y = self.x + dx, self.y + dy
hero = Player.spawn_at_origin("hero")
orc = Player("orc", x=5, y=2)
orc.take_damage(30)
hero.take_damage(250)
print(hero.health, hero.is_alive, orc.health, orc.is_alive)
Player.max_health = 150
print(Player("elf").health, orc.health)
orc.move(-2, 4)
print(orc.x, orc.y)
print(Player.count, Player.clamp(7, 0, 5))
print(sorted(vars(orc)))
# TODO: write your prediction for each print before you run it
Hint 1

clamp keeps a value between low and high. What is clamp(100 - 250, 0, 100)?

Hint 2

self.health = self.max_health copies the class value into the instance when the player is created. Does a later change to Player.max_health change that copy?

Solution
from typing import Self
class Player:
max_health = 100
count = 0
def __init__(self, name: str, x: int = 0, y: int = 0):
self.name = name
self.x, self.y = x, y
self.health = self.max_health
Player.count += 1
@classmethod
def spawn_at_origin(cls, name: str) -> Self:
return cls(name)
@staticmethod
def clamp(value: int, low: int, high: int) -> int:
return max(low, min(value, high))
@property
def is_alive(self) -> bool:
return self.health > 0
def take_damage(self, amount: int) -> None:
self.health = self.clamp(self.health - amount, 0, self.max_health)
def move(self, dx: int, dy: int) -> None:
self.x, self.y = self.x + dx, self.y + dy
hero = Player.spawn_at_origin("hero")
orc = Player("orc", x=5, y=2)
orc.take_damage(30)
hero.take_damage(250)
print(hero.health, hero.is_alive, orc.health, orc.is_alive)
Player.max_health = 150
print(Player("elf").health, orc.health)
orc.move(-2, 4)
print(orc.x, orc.y)
print(Player.count, Player.clamp(7, 0, 5))
print(sorted(vars(orc)))
assert hero.health == 0 and not hero.is_alive
assert "max_health" not in vars(orc)
Output
0 False 70 True
150 70
3 6
3 5
['health', 'name', 'x', 'y']

How it works:

  1. hero loses 250 of 100 health. clamp(-150, 0, 100) gives 0, so the hero is dead. The orc has 100 − 30 = 70.
  2. The elf is created after Player.max_health became 150, so it starts with 150. The orc keeps its stored 70: health is an instance attribute, copied once in __init__.
  3. move changes the orc’s own position: (5 − 2, 2 + 4) = (3, 6).
  4. Three players were created (hero, orc, elf). The class method spawn_at_origin calls cls(name), so it also runs __init__ and counts. clamp(7, 0, 5) is 5.
  5. vars(orc) holds only instance data. max_health, count and the methods live in the class.

Alternative: if every player should always use the current maximum, do not copy it: compute health as a fraction of self.max_health, or check the limit only when you heal. This is the same choice as a stored attribute versus a property.

M18-C06 · Interpret: where does each attribute live?

Section titled “M18-C06 · Interpret: where does each attribute live?”
Core

Interpret: a teammate’s Scaler class behaves strangely. Run the code in the starter, read its output and answer the three questions in comments. Then prove each answer with an assert.

  1. Why does b.fitted print True, although b.fit was never called?
  2. Why does a.mean print 22.05 but b.mean print 0.0?
  3. Which single change makes b.fitted False? Write the fixed class as FixedScaler, fit one instance, create a second one and print the fitted value of both.
Expected output
22.05 True
0.0 True
['mean'] []
True False
Starter
from typing import Self
class Scaler:
mean = 0.0
state = {"fitted": False}
def fit(self, values: list[float]) -> Self:
self.mean = round(sum(values) / len(values), 2)
self.state["fitted"] = True
return self
@property
def fitted(self) -> bool:
return self.state["fitted"]
a = Scaler().fit([20.21, 21.47, 24.47]) # S1 temperatures
b = Scaler()
print(a.mean, a.fitted)
print(b.mean, b.fitted)
print(sorted(vars(a)), sorted(vars(b)))
# TODO: answer the three questions in comments
# TODO: add one assert per answer
# TODO: write FixedScaler, then print(fixed_a.fitted, fixed_b.fitted)
Hint 1

Look at the last line of output. Which names are in vars(a)? Which are in vars(b)?

Hint 2

self.mean = ... is an assignment. self.state["fitted"] = True changes an item of a dict that self.state finds. Which one creates an instance attribute?

Solution
from typing import Self
class Scaler:
mean = 0.0
state = {"fitted": False}
def fit(self, values: list[float]) -> Self:
self.mean = round(sum(values) / len(values), 2)
self.state["fitted"] = True
return self
@property
def fitted(self) -> bool:
return self.state["fitted"]
a = Scaler().fit([20.21, 21.47, 24.47]) # S1 temperatures
b = Scaler()
print(a.mean, a.fitted)
print(b.mean, b.fitted)
print(sorted(vars(a)), sorted(vars(b)))
# 1. state is one dict on the class. a.fit() changed it in place, so every Scaler
# (b too) now reads fitted = True.
assert a.state is b.state is Scaler.state
# 2. self.mean = ... is an assignment, so it created an instance attribute on a.
# b has none and falls back to the class value 0.0.
assert "mean" in vars(a) and "mean" not in vars(b)
# 3. Create the dict per instance in __init__.
class FixedScaler:
mean = 0.0
def __init__(self):
self.state = {"fitted": False} # one dict per instance
def fit(self, values: list[float]) -> Self:
self.mean = round(sum(values) / len(values), 2)
self.state["fitted"] = True
return self
@property
def fitted(self) -> bool:
return self.state["fitted"]
fixed_a = FixedScaler().fit([20.21, 21.47, 24.47])
fixed_b = FixedScaler()
print(fixed_a.fitted, fixed_b.fitted)
assert fixed_a.fitted and not fixed_b.fitted
assert fixed_a.state is not fixed_b.state
Output
22.05 True
0.0 True
['mean'] []
True False

How it works:

  1. The two class attributes behave differently because the code uses them differently. mean is rebound with =, which creates an instance attribute. state is changed in place, which never creates one.
  2. vars(a) contains only mean. vars(b) is empty. So b.fitted reads the one shared dict, which a.fit() already changed.
  3. FixedScaler is Scaler with one added __init__ that gives each instance its own dict. Now fixed_a.fit() changes only the dict of fixed_a, and the last assert proves that the two dicts are separate objects.

Alternative: drop the dict. Set the learned attribute self.mean_ = ... only in fit, and make fitted return hasattr(self, "mean_"). This is the scikit-learn convention, and it has no shared state at all.

M18-C07 · Choose and justify: which kind of method?

Section titled “M18-C07 · Choose and justify: which kind of method?”
Core

Choose and justify: a SensorLog class holds the readings of one sensor from data/sensors.csv. It needs four helpers. For each one, choose an instance method, a property, a class method or a static method, and write one comment that justifies the choice. Then implement the class and run it on sensor S3 for 2024-05-01.

  1. parse_time(text): turn "2024-05-01T13:30:00" into the minutes since midnight (810).
  2. from_csv(path, sensor_id, day): build a SensorLog from the file.
  3. mean_temperature: the mean of the non-blank temperatures of this log, rounded to 2 decimals.
  4. readings_between(start, end): the temperatures of the readings with start <= minutes < end.
Expected output
S3 144 readings
mean: 21.29
03:00-04:00: [19.18, 19.52, 19.63, 19.22, 19.25, 19.07]
Starter
import csv
class SensorLog:
def __init__(self, sensor_id: str, minutes: list[int], temps: list[float | None]):
self.sensor_id = sensor_id
self.minutes = minutes # minutes since midnight, one per reading
self.temps = temps # temperature_c, None for a blank cell
# TODO: parse_time, from_csv, mean_temperature, readings_between
# TODO: one comment per helper that justifies its kind
log = SensorLog.from_csv("data/sensors.csv", sensor_id="S3", day="2024-05-01")
# TODO: print the number of readings, the mean temperature and the readings 03:00-04:00
Hint 1

Ask two questions per helper: does it need the data of one log (self)? Does it create a new log (cls)?

Hint 2

parse_time needs neither. from_csv creates an instance. mean_temperature takes no arguments and reads like a value. readings_between takes arguments and reads the log.

Solution
import csv
from typing import Self
class SensorLog:
def __init__(self, sensor_id: str, minutes: list[int], temps: list[float | None]):
self.sensor_id = sensor_id
self.minutes = minutes # minutes since midnight, one per reading
self.temps = temps # temperature_c, None for a blank cell
@staticmethod
def parse_time(text: str) -> int:
# Static: a pure text-to-number helper; needs no log and no class.
hours, minutes = text[11:13], text[14:16]
return int(hours) * 60 + int(minutes)
@classmethod
def from_csv(cls, path: str, sensor_id: str, day: str) -> Self:
# Class method: an alternative constructor; it creates a new log.
minutes, temps = [], []
with open(path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
if row["sensor_id"] == sensor_id and row["timestamp"].startswith(day):
minutes.append(cls.parse_time(row["timestamp"]))
text = row["temperature_c"]
temps.append(float(text) if text else None)
return cls(sensor_id, minutes, temps)
@property
def mean_temperature(self) -> float:
# Property: no arguments, cheap, reads like a value of this log.
valid = [t for t in self.temps if t is not None]
return round(sum(valid) / len(valid), 2)
def readings_between(self, start: int, end: int) -> list[float | None]:
# Instance method: it needs this log's data and takes arguments.
return [t for m, t in zip(self.minutes, self.temps) if start <= m < end]
log = SensorLog.from_csv("data/sensors.csv", sensor_id="S3", day="2024-05-01")
print(log.sensor_id, len(log.minutes), "readings")
print("mean:", log.mean_temperature)
print("03:00-04:00:", log.readings_between(180, 240))
assert SensorLog.parse_time("2024-05-01T13:30:00") == 810
assert len(log.minutes) == 144 # 24 hours x 6 readings per hour
assert len(log.readings_between(180, 240)) == 6
Output
S3 144 readings
mean: 21.29
03:00-04:00: [19.18, 19.52, 19.63, 19.22, 19.25, 19.07]

How it works:

  1. parse_time works on a string only, so it is static. The slices [11:13] and [14:16] cut the hour and the minute out of the ISO timestamp.
  2. from_csv reads the file and ends with cls(...), the pattern of every alternative constructor.
  3. mean_temperature skips the None values, so a blank cell does not break the mean.
  4. readings_between pairs each minute with its temperature through zip and keeps the readings in the half-open interval (module 03). One day of 10-minute readings gives 144 rows.

Alternative: parse_time could use datetime.fromisoformat(text) (module 09), itself a class method, and return dt.hour * 60 + dt.minute. It is slower but rejects malformed text.

M18-C08 · Vibration alerts with shared and per-sensor thresholds

Section titled “M18-C08 · Vibration alerts with shared and per-sensor thresholds”
Core

Write a class VibrationMonitor. A class attribute warn_mm_s = 4.5 is the default threshold. Each monitor has a sensor_id and a list of alert timestamps. A method check(timestamp, vibration) adds the timestamp when the vibration is at or above the threshold (skip None), and a property n_alerts returns the count. Run four monitors over the readings of data/sensors.csv from 2024-05-12 on. Sensor S4 is known to be wearing out, so the maintenance team raised its threshold to 6.0 for this report. Print the alerts per sensor and the first S4 alert.

Expected output
S1: 2 alerts (threshold 4.5)
S2: 2 alerts (threshold 4.5)
S3: 0 alerts (threshold 4.5)
S4: 269 alerts (threshold 6.0)
first S4 alert: 2024-05-12T06:30:00
Starter
import csv
class VibrationMonitor:
warn_mm_s = 4.5 # default threshold, mm/s
# TODO: __init__ with sensor_id and an empty list of alerts
# TODO: check(timestamp, vibration) and the property n_alerts
# TODO: one monitor per sensor S1-S4, with a threshold of 6.0 for S4 only
# TODO: feed every row from 2024-05-12 on to the monitor of its sensor
# TODO: print "S1: 2 alerts (threshold 4.5)" etc., then the first S4 alert
Hint 1

Keep the monitors in a dict keyed by sensor id: monitors = {sid: VibrationMonitor(sid) for sid in ("S1", "S2", "S3", "S4")}.

Hint 2

monitors["S4"].warn_mm_s = 6.0 overrides the threshold for S4 only. ISO timestamps compare correctly as strings: row["timestamp"] >= "2024-05-12".

Solution
import csv
class VibrationMonitor:
warn_mm_s = 4.5 # default threshold, mm/s
def __init__(self, sensor_id: str):
self.sensor_id = sensor_id
self.alerts: list[str] = [] # timestamps of alerts, one list per monitor
def check(self, timestamp: str, vibration: float | None) -> None:
if vibration is not None and vibration >= self.warn_mm_s:
self.alerts.append(timestamp)
@property
def n_alerts(self) -> int:
return len(self.alerts)
monitors = {sid: VibrationMonitor(sid) for sid in ("S1", "S2", "S3", "S4")}
monitors["S4"].warn_mm_s = 6.0 # override for the worn sensor only
with open("data/sensors.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
if row["timestamp"] >= "2024-05-12":
text = row["vibration_mm_s"]
value = float(text) if text else None
monitors[row["sensor_id"]].check(row["timestamp"], value)
for m in monitors.values():
print(f"{m.sensor_id}: {m.n_alerts} alerts (threshold {m.warn_mm_s})")
print("first S4 alert:", monitors["S4"].alerts[0])
assert VibrationMonitor.warn_mm_s == 4.5
assert vars(monitors["S4"])["warn_mm_s"] == 6.0
assert "warn_mm_s" not in vars(monitors["S1"])
Output
S1: 2 alerts (threshold 4.5)
S2: 2 alerts (threshold 4.5)
S3: 0 alerts (threshold 4.5)
S4: 269 alerts (threshold 6.0)
first S4 alert: 2024-05-12T06:30:00

How it works:

  1. The default threshold is a class attribute, so three monitors share it. The S4 monitor gets its own instance attribute, which shadows the default.
  2. self.warn_mm_s inside check follows the normal lookup: the instance first, then the class. The same method uses 6.0 for S4 and 4.5 for the others.
  3. Each monitor creates its own alerts list in __init__, so the alerts of one sensor never appear in another.
  4. Even with the higher threshold, S4 has far more alerts than the other sensors, which confirms the wear that starts on May 12.

Alternative: pass the threshold to the initializer with the class default as fallback: def __init__(self, sensor_id, warn_mm_s=None) and if warn_mm_s is not None: self.warn_mm_s = warn_mm_s. Then the override is visible where the monitor is created.

M18-C09 · Experiment ids from a class counter

Section titled “M18-C09 · Experiment ids from a class counter”
Core

Write a class Experiment that gives each new experiment an id EXP-001, EXP-002 and so on, from a class attribute _next_number. Add a class method reset_ids(start=1) that sets the counter, for example at the start of a test, and a class method from_config(config) that builds an experiment from a dict with the keys "model" and "params". Create three experiments, reset the counter, and create one more.

Expected output
EXP-001 knn {'n_neighbors': 5}
EXP-002 linear {}
EXP-003 knn {'n_neighbors': 15}
EXP-100 101
Starter
class Experiment:
_next_number = 1 # shared by all experiments
def __init__(self, model: str, params: dict[str, float]):
# TODO: take the next id from the class counter, then increase it
self.model = model
self.params = params
# TODO: class methods reset_ids(start=1) and from_config(config)
runs = [
Experiment("knn", {"n_neighbors": 5}),
Experiment("linear", {}),
Experiment.from_config({"model": "knn", "params": {"n_neighbors": 15}}),
]
# TODO: print the id, model and params of each run
# TODO: reset the ids to 100 and create one more experiment
Hint 1

Format the id with f"EXP-{number:03d}". The :03d spec pads the number to 3 digits.

Hint 2

Inside a class method, change the counter with cls._next_number = start. Inside __init__, use type(self)._next_number or Experiment._next_number.

Solution
from typing import Self
class Experiment:
_next_number = 1 # shared by all experiments
def __init__(self, model: str, params: dict[str, float]):
cls = type(self)
self.experiment_id = f"EXP-{cls._next_number:03d}"
cls._next_number += 1
self.model = model
self.params = dict(params) # a copy: the caller's dict stays separate
@classmethod
def reset_ids(cls, start: int = 1) -> None:
cls._next_number = start
@classmethod
def from_config(cls, config: dict) -> Self:
return cls(config["model"], config.get("params", {}))
runs = [
Experiment("knn", {"n_neighbors": 5}),
Experiment("linear", {}),
Experiment.from_config({"model": "knn", "params": {"n_neighbors": 15}}),
]
for run in runs:
print(run.experiment_id, run.model, run.params)
Experiment.reset_ids(start=100)
extra = Experiment("linear", {})
print(extra.experiment_id, Experiment._next_number)
assert [r.experiment_id for r in runs] == ["EXP-001", "EXP-002", "EXP-003"]
assert "_next_number" not in vars(extra)
Output
EXP-001 knn {'n_neighbors': 5}
EXP-002 linear {}
EXP-003 knn {'n_neighbors': 15}
EXP-100 101

How it works:

  1. type(self) is the class of the new object. Reading and writing cls._next_number changes the one shared counter, not an instance attribute.
  2. reset_ids is a class method, because it changes class-wide state and needs no instance.
  3. from_config is an alternative constructor. It ends in cls(...), so it also takes an id.
  4. dict(params) copies the dict. Without the copy, two experiments built from the same params dict would share it, the aliasing problem of module 04.

Alternative: itertools.count(1) stored as a class attribute gives the numbers without += 1: _numbers = count(1) and next(type(self)._numbers). Resetting then means replacing the counter: cls._numbers = count(start).

M18-C10 · A label encoder with learned attributes

Section titled “M18-C10 · A label encoder with learned attributes”
Core

ML models need numbers, so text labels are encoded as integers. Write a class LabelEncoder in the scikit-learn style. fit(labels) learns the sorted unique labels into classes_ and returns self. transform(labels) returns the index of each label in classes_. inverse_transform(codes) turns codes back into labels. Both raise NotFittedError (a subclass of ValueError) before fit, and transform raises ValueError for a label it has not seen. Fit it on the plan column of data/customers.csv.

Expected output
NotFittedError: LabelEncoder is not fitted yet; call fit() first
['basic', 'premium', 'standard']
['premium', 'standard', 'premium', 'premium', 'basic'] -> [1, 2, 1, 1, 0]
['standard', 'basic']
ValueError: unseen labels: ['gold']
Starter
import csv
class NotFittedError(ValueError):
"""Raised when a model is used before fit()."""
class LabelEncoder:
# TODO: fit, transform, inverse_transform and a private _check_fitted
...
with open("data/customers.csv", newline="", encoding="utf-8") as f:
plans = [row["plan"] for row in csv.DictReader(f)]
# TODO: try transform before fit; then fit, print classes_, encode the first 5 plans
# TODO: decode [2, 0] and try to encode "gold"
Hint 1

sorted(set(labels)) gives the unique labels in order. Keep a dict from label to index too, so transform is fast: {label: i for i, label in enumerate(self.classes_)}.

Hint 2

The fitted check is hasattr(self, "classes_"). Do not create classes_ in __init__.

Solution
import csv
from typing import Self
class NotFittedError(ValueError):
"""Raised when a model is used before fit()."""
class LabelEncoder:
def fit(self, labels: list[str]) -> Self:
self.classes_ = sorted(set(labels))
self._index = {label: i for i, label in enumerate(self.classes_)}
return self
def transform(self, labels: list[str]) -> list[int]:
self._check_fitted()
unknown = sorted(set(labels) - set(self._index))
if unknown:
raise ValueError(f"unseen labels: {unknown}")
return [self._index[label] for label in labels]
def inverse_transform(self, codes: list[int]) -> list[str]:
self._check_fitted()
return [self.classes_[code] for code in codes]
def _check_fitted(self) -> None:
if not hasattr(self, "classes_"):
raise NotFittedError("LabelEncoder is not fitted yet; call fit() first")
with open("data/customers.csv", newline="", encoding="utf-8") as f:
plans = [row["plan"] for row in csv.DictReader(f)]
try:
LabelEncoder().transform(plans)
except NotFittedError as exc:
print("NotFittedError:", exc)
encoder = LabelEncoder().fit(plans)
codes = encoder.transform(plans)
print(encoder.classes_)
print(plans[:5], "->", codes[:5])
print(encoder.inverse_transform([2, 0]))
try:
encoder.transform(["basic", "gold"])
except ValueError as exc:
print("ValueError:", exc)
assert encoder.inverse_transform(codes) == plans
assert isinstance(NotFittedError("x"), ValueError)
Output
NotFittedError: LabelEncoder is not fitted yet; call fit() first
['basic', 'premium', 'standard']
['premium', 'standard', 'premium', 'premium', 'basic'] -> [1, 2, 1, 1, 0]
['standard', 'basic']
ValueError: unseen labels: ['gold']

How it works:

  1. fit sets the learned attributes. classes_ is public and ends with _, the scikit-learn sign of a learned value. _index is an internal helper, so it starts with _.
  2. fit returns self, so LabelEncoder().fit(plans) gives the fitted encoder in one line.
  3. transform first checks the fit, then rejects unknown labels with a clear list, then looks up each label in the dict.
  4. The first assert is a round trip: decoding the codes gives back the original 5,000 labels.

Alternative: scikit-learn’s sklearn.preprocessing.LabelEncoder has the same interface and also sorts the classes. Use it in real projects (module 33). For features, as opposed to a target, prefer OneHotEncoder, because integer codes suggest an order (basic < premium < standard) that does not exist.

M18-C11 · Fix the bug: the property that calls itself

Section titled “M18-C11 · Fix the bug: the property that calls itself”
Core

Fix the bug: a ResampleRule sets the bucket size, in minutes, for resampling the 10-minute readings of data/sensors.csv. A bucket must be a positive multiple of 10. Creating a rule crashes with RecursionError: maximum recursion depth exceeded. Fix the class, then show one valid rule and one rejected value.

Expected output
60 6 {'_minutes': 60}
rejected: minutes must be a positive multiple of 10, got 25
Starter
class ResampleRule:
def __init__(self, minutes: int):
self.minutes = minutes
@property
def minutes(self) -> int:
return self.minutes
@minutes.setter
def minutes(self, value: int) -> None:
if value <= 0 or value % 10 != 0:
raise ValueError(f"minutes must be a positive multiple of 10, got {value}")
self.minutes = value
@property
def readings_per_bucket(self) -> int:
return self.minutes // 10
hourly = ResampleRule(60)
print(hourly.minutes, hourly.readings_per_bucket)
# TODO: fix the property so that the rule works, then try ResampleRule(25)
Hint 1

Follow self.minutes = value inside the setter. Which method does that line call?

Hint 2

The getter has the same problem as the setter. Both must use another attribute name for the stored value.

Solution
class ResampleRule:
def __init__(self, minutes: int):
self.minutes = minutes # runs the setter: correct
@property
def minutes(self) -> int:
return self._minutes
@minutes.setter
def minutes(self, value: int) -> None:
if value <= 0 or value % 10 != 0:
raise ValueError(f"minutes must be a positive multiple of 10, got {value}")
self._minutes = value
@property
def readings_per_bucket(self) -> int:
return self.minutes // 10
hourly = ResampleRule(60)
print(hourly.minutes, hourly.readings_per_bucket, vars(hourly))
try:
ResampleRule(25)
except ValueError as exc:
print("rejected:", exc)
assert ResampleRule(1440).readings_per_bucket == 144
assert vars(hourly) == {"_minutes": 60}
Output
60 6 {'_minutes': 60}
rejected: minutes must be a positive multiple of 10, got 25

How it works:

  1. In the bug, self.minutes = value inside the setter assigns to the property again, so the setter calls itself without end. Python stops it with RecursionError after about 1,000 calls.
  2. The getter had the same loop: return self.minutes calls the getter.
  3. The fix stores the value as self._minutes. That is a plain instance attribute, not the property, so there is no loop.
  4. self.minutes = minutes in __init__ must stay as it is: it is the line that runs the validation for new objects.

Alternative: if the bucket size never changes after creation, validate it once in __init__ and store it as a plain attribute, or use a frozen dataclass (module 21). A property is worth it when later assignments must be checked too.

Core

Text models turn words into integer ids with a vocabulary: a mapping from each known word (token) to an id. Write a class Vocabulary. A static method tokenize(text) lowercases the text and keeps runs of letters with re.findall(r"[a-z]+", ...). A class method from_texts(texts, min_count=2) counts the tokens and keeps those that appear at least min_count times, sorted alphabetically, with ids from 1; id 0 is reserved for unknown words. Add a property size (known words plus 1) and a method encode(text). Build it from the first 200 review texts of data/reviews.csv. Print the vocabulary size, the tokens of "LOVE IT!!! Easy to use.", the ids of that text and the ids of "Zebra-striped quantum toaster".

Expected output
vocabulary size: 264
['love', 'it', 'easy', 'to', 'use']
[127, 114, 66, 234, 242]
[0, 0, 0, 0]
Starter
import csv
import re
from collections import Counter
class Vocabulary:
unknown_id = 0
def __init__(self, tokens: list[str]):
# TODO: map each token to an id from 1
...
# TODO: static method tokenize, class method from_texts, property size, encode
with open("data/reviews.csv", newline="", encoding="utf-8") as f:
texts = [row["text"] for _, row in zip(range(200), csv.DictReader(f))]
# TODO: build the vocabulary (min_count=2) and print "vocabulary size: ..."
# TODO: print the tokens and the ids of "LOVE IT!!! Easy to use."
# TODO: print the ids of "Zebra-striped quantum toaster"
Hint 1

Counter() counts the tokens; counter.update(tokens) adds the tokens of one text. Keep [t for t, n in counter.items() if n >= min_count] and sort it.

Hint 2

In __init__, build self._ids = {token: i for i, token in enumerate(tokens, start=1)}. encode uses self._ids.get(token, self.unknown_id).

Solution
import csv
import re
from collections import Counter
from typing import Self
class Vocabulary:
unknown_id = 0 # id for every word that is not in the vocabulary
def __init__(self, tokens: list[str]):
self._ids = {token: i for i, token in enumerate(tokens, start=1)}
@staticmethod
def tokenize(text: str) -> list[str]:
return re.findall(r"[a-z]+", text.lower())
@classmethod
def from_texts(cls, texts: list[str], min_count: int = 2) -> Self:
counts: Counter[str] = Counter()
for text in texts:
counts.update(cls.tokenize(text))
kept = sorted(token for token, n in counts.items() if n >= min_count)
return cls(kept)
@property
def size(self) -> int:
return len(self._ids) + 1 # + 1 for the unknown id
def encode(self, text: str) -> list[int]:
return [self._ids.get(t, self.unknown_id) for t in self.tokenize(text)]
with open("data/reviews.csv", newline="", encoding="utf-8") as f:
texts = [row["text"] for _, row in zip(range(200), csv.DictReader(f))]
vocab = Vocabulary.from_texts(texts, min_count=2)
print("vocabulary size:", vocab.size)
print(Vocabulary.tokenize("LOVE IT!!! Easy to use."))
print(vocab.encode("LOVE IT!!! Easy to use."))
print(vocab.encode("Zebra-striped quantum toaster"))
assert vocab.encode("") == []
assert Vocabulary.from_texts(["a b", "a"], min_count=2).size == 2
Output
vocabulary size: 264
['love', 'it', 'easy', 'to', 'use']
[127, 114, 66, 234, 242]
[0, 0, 0, 0]

How it works:

  1. tokenize needs no vocabulary, so it is static. The class method and encode both call it, so the two always split text the same way.
  2. from_texts does the counting and filtering, then calls cls(kept). __init__ only builds the lookup dict from a clean token list, which makes it easy to test.
  3. Words seen fewer than min_count times are dropped. Rare words add many ids and teach a model little.
  4. encode maps unknown words to 0, so the made-up product words all become 0.

Alternative: scikit-learn’s CountVectorizer (module 41) builds a vocabulary with min_df and a token pattern, and turns texts into count vectors. The idea is the same; the class above shows what happens inside.

M18-X01 · Streaming anomaly detection per sensor

Section titled “M18-X01 · Streaming anomaly detection per sensor”
Challenge

A monitoring service reads data/sensors.csv row by row, in time order, and must flag temperature anomalies: values far from the usual values of their own sensor. Build it from two classes.

  1. RunningStats: the Welford running mean and population standard deviation of the lesson, with update(value) and read-only properties count, mean and std.
  2. ZScoreDetector: keeps one RunningStats per sensor in a dict. Its z-score of a value is |value - mean| / std, the distance from the mean in standard deviations. Validated properties: threshold (a number > 0) and warmup (an int ≥ 2, the number of readings a sensor needs before it can flag anything). A method check(sensor_id, timestamp, value) returns True and records the anomaly when the sensor is warmed up and the z-score is above the threshold. Otherwise it updates the statistics. Anomalies are not added to the statistics, so a spike cannot distort the mean.

Run it with threshold=4.0 and warmup=144 (one day). Skip blank temperatures. Print the count per sensor, the total and the largest anomaly.

Expected output
S1: 8 anomalies
S2: 11 anomalies
S3: 10 anomalies
S4: 8 anomalies
total: 37
largest: ('S4', '2024-05-03T16:00:00', 44.36, 11.6)
rejected: warmup must be >= 2, got 1
Starter
import csv
import math
class RunningStats:
# TODO: Welford update, count, mean, std (population)
...
class ZScoreDetector:
def __init__(self, threshold: float = 4.0, warmup: int = 144):
self.threshold = threshold
self.warmup = warmup
# TODO: a dict of RunningStats per sensor and a list of anomalies
# TODO: validated properties threshold and warmup
# TODO: check(sensor_id, timestamp, value) -> bool
# TODO: feed every non-blank temperature to the detector
# TODO: print the anomalies per sensor, the total and the largest one
Hint 1

Get or create the statistics of a sensor with self._stats.setdefault(sensor_id, RunningStats()). Store each anomaly as a tuple (sensor_id, timestamp, value, z).

Hint 2

In check, compute the z-score only when stats.count >= self.warmup and stats.std > 0. If it is above the threshold, record it and return True without calling update. The largest anomaly is max(anomalies, key=lambda a: a[3]).

Solution
import csv
import math
from collections import Counter
class RunningStats:
"""Running mean and population standard deviation (Welford)."""
def __init__(self):
self._count = 0
self._mean = 0.0
self._m2 = 0.0
def update(self, value: float) -> None:
self._count += 1
delta = value - self._mean
self._mean += delta / self._count
self._m2 += delta * (value - self._mean)
@property
def count(self) -> int:
return self._count
@property
def mean(self) -> float:
return self._mean
@property
def std(self) -> float:
return math.sqrt(self._m2 / self._count) if self._count else 0.0
class ZScoreDetector:
def __init__(self, threshold: float = 4.0, warmup: int = 144):
self.threshold = threshold
self.warmup = warmup
self._stats: dict[str, RunningStats] = {}
self.anomalies: list[tuple[str, str, float, float]] = []
@property
def threshold(self) -> float:
return self._threshold
@threshold.setter
def threshold(self, value: float) -> None:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError(f"threshold must be a number, got {value!r}")
if value <= 0:
raise ValueError(f"threshold must be > 0, got {value}")
self._threshold = value
@property
def warmup(self) -> int:
return self._warmup
@warmup.setter
def warmup(self, value: int) -> None:
if isinstance(value, bool) or not isinstance(value, int):
raise TypeError(f"warmup must be an int, got {value!r}")
if value < 2:
raise ValueError(f"warmup must be >= 2, got {value}")
self._warmup = value
def check(self, sensor_id: str, timestamp: str, value: float) -> bool:
stats = self._stats.setdefault(sensor_id, RunningStats())
if stats.count >= self.warmup and stats.std > 0:
z = abs(value - stats.mean) / stats.std
if z > self.threshold:
self.anomalies.append((sensor_id, timestamp, value, round(z, 1)))
return True # do not let the spike distort the statistics
stats.update(value)
return False
detector = ZScoreDetector(threshold=4.0, warmup=144)
with open("data/sensors.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
text = row["temperature_c"]
if text: # skip blank cells
detector.check(row["sensor_id"], row["timestamp"], float(text))
per_sensor = Counter(a[0] for a in detector.anomalies)
for sensor_id in sorted(per_sensor):
print(f"{sensor_id}: {per_sensor[sensor_id]} anomalies")
print("total:", len(detector.anomalies))
print("largest:", max(detector.anomalies, key=lambda a: a[3]))
try:
detector.warmup = 1
except ValueError as exc:
print("rejected:", exc)
assert all(a[3] > 4.0 for a in detector.anomalies)
assert detector.warmup == 144
assert len({a[0] for a in detector.anomalies}) == 4
Output
S1: 8 anomalies
S2: 11 anomalies
S3: 10 anomalies
S4: 8 anomalies
total: 37
largest: ('S4', '2024-05-03T16:00:00', 44.36, 11.6)
rejected: warmup must be >= 2, got 1

How it works:

  1. Composition: an object that holds other objects and delegates work to them. The detector does not compute statistics itself. It owns one RunningStats object per sensor and asks it for count, mean and std. Each class has one job.
  2. Per-sensor state: setdefault creates the statistics of a sensor on its first reading. S4 runs warmer than S1, so one shared mean would flag normal S4 readings.
  3. Warm-up: with fewer than 144 readings, the mean and the standard deviation are not reliable, so the detector only learns.
  4. No contamination: an anomaly is recorded but not added to the statistics. One spike of +15 °C would otherwise raise the mean and the standard deviation and hide the next spike.
  5. Validation: the setters protect the two settings for the whole life of the detector, as the rejected warmup = 1 shows.

Alternative: pandas (module 25) computes a rolling mean and standard deviation per sensor with groupby("sensor_id")["temperature_c"].rolling(144). That is faster for a file on disk. The streaming class wins when readings arrive one at a time from a live feed and you cannot keep them all.

M18-X02 · Refactor a churn rule into a model class

Section titled “M18-X02 · Refactor a churn rule into a model class”
Challenge

Refactor: turn the churn analysis in the starter into a model class with the scikit-learn interface. GroupRateModel learns the churn rate of each group of customers, where a group is the pair (contract, tenure_months <= 6).

  • fit(rows) learns rates_ (a dict from group to churn rate) and base_rate_ (the overall rate, used for a group not seen in training). It returns self.
  • predict_proba(rows) returns the learned rate of each row’s group. predict(rows) returns 1 when that rate is at least threshold, else 0.
  • __init__(threshold=0.5) stores threshold unchanged, under the same name: this is the scikit-learn rule for estimators (see the lesson’s Example 5). A private method _validate_params() checks it at the start of fit and predict: a wrong type raises TypeError, a number outside 0 to 1 raises ValueError.
  • Both predict methods raise NotFittedError before fit.

Split data/customers.csv deterministically: every fifth row (index 0, 5, 10…) is the test set, the rest is the training set. Print the learned rates, then the accuracy and the recall (the share of real churners that the model flags) on the test set for the thresholds 0.5 and 0.3. Then set threshold = 1.5 and show the error that predict raises. Explain the result in a comment.

Expected output
month-to-month new=False churn rate 0.201
month-to-month new=True churn rate 0.469
one-year new=False churn rate 0.085
one-year new=True churn rate 0.167
two-year new=False churn rate 0.030
two-year new=True churn rate 0.069
base rate 0.194
threshold 0.5: flagged 0, accuracy 0.813, recall 0.000
threshold 0.3: flagged 208, accuracy 0.799, recall 0.519
ValueError: threshold must be in [0, 1], got 1.5
Starter
import csv
with open("data/customers.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
# Procedural version: churn rate per group, on all rows
counts = {}
for row in rows:
group = (row["contract"], int(row["tenure_months"]) <= 6)
n, churned = counts.get(group, (0, 0))
counts[group] = (n + 1, churned + int(row["churned"]))
for group, (n, churned) in sorted(counts.items()):
print(group, round(churned / n, 3))
# TODO: a NotFittedError class and a GroupRateModel class
# TODO: split into train (index % 5 != 0) and test (index % 5 == 0)
# TODO: fit on train; print rates_; print accuracy and recall for thresholds 0.5 and 0.3
# TODO: set model.threshold = 1.5 and print the ValueError that predict raises
Hint 1

Write a static method _group(row) that returns the pair. Both fit and predict_proba call it, so the grouping rule lives in one place.

Hint 2

Accuracy is the share of predictions equal to the truth. Recall is (rows with prediction 1 and truth 1) / (rows with truth 1). Change the threshold on the fitted model with model.threshold = 0.3; you do not need to fit again.

Hint 3

At threshold 0.5, look at the largest learned rate. Can any group reach 0.5? What does the model predict for every customer then?

Solution
import csv
from typing import Self
class NotFittedError(ValueError):
"""Raised when a model is used before fit()."""
class GroupRateModel:
"""Predict churn from the training churn rate of (contract, is_new) groups."""
def __init__(self, threshold: float = 0.5):
self.threshold = threshold # stored unchanged; checked in fit and predict
def _validate_params(self) -> None:
value = self.threshold
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError(f"threshold must be a number, got {value!r}")
if not 0 <= value <= 1:
raise ValueError(f"threshold must be in [0, 1], got {value}")
@staticmethod
def _group(row: dict[str, str]) -> tuple[str, bool]:
return row["contract"], int(row["tenure_months"]) <= 6
def fit(self, rows: list[dict[str, str]]) -> Self:
self._validate_params()
counts: dict[tuple[str, bool], list[int]] = {}
for row in rows:
counts.setdefault(self._group(row), []).append(int(row["churned"]))
self.rates_ = {g: sum(v) / len(v) for g, v in sorted(counts.items())}
self.base_rate_ = sum(int(r["churned"]) for r in rows) / len(rows)
return self
def predict_proba(self, rows: list[dict[str, str]]) -> list[float]:
if not hasattr(self, "rates_"):
raise NotFittedError("GroupRateModel is not fitted yet; call fit() first")
return [self.rates_.get(self._group(r), self.base_rate_) for r in rows]
def predict(self, rows: list[dict[str, str]]) -> list[int]:
self._validate_params()
return [int(p >= self.threshold) for p in self.predict_proba(rows)]
with open("data/customers.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
train = [row for i, row in enumerate(rows) if i % 5 != 0]
test = [row for i, row in enumerate(rows) if i % 5 == 0]
y_test = [int(row["churned"]) for row in test]
model = GroupRateModel().fit(train)
for (contract, is_new), rate in model.rates_.items():
print(f"{contract:<15} new={is_new!s:<5} churn rate {rate:.3f}")
print(f"base rate {model.base_rate_:.3f}")
for threshold in (0.5, 0.3):
model.threshold = threshold
pred = model.predict(test)
accuracy = sum(p == t for p, t in zip(pred, y_test)) / len(y_test)
recall = sum(p and t for p, t in zip(pred, y_test)) / sum(y_test)
print(f"threshold {threshold}: flagged {sum(pred):>3}, "
f"accuracy {accuracy:.3f}, recall {recall:.3f}")
model.threshold = 1.5 # accepted here, like a scikit-learn parameter
try:
model.predict(test)
except ValueError as exc:
print("ValueError:", exc)
# At 0.5 no group reaches the threshold, so the model predicts "no churn" for
# everyone: accuracy equals the share of loyal customers and recall is 0.
# At 0.3 the model flags new month-to-month customers. Accuracy drops a little,
# but the model now finds about half of the churners. Accuracy alone misleads
# on imbalanced classes.
assert max(model.rates_.values()) < 0.5
assert len(train) == 4000 and len(test) == 1000
Output
month-to-month new=False churn rate 0.201
month-to-month new=True churn rate 0.469
one-year new=False churn rate 0.085
one-year new=True churn rate 0.167
two-year new=False churn rate 0.030
two-year new=True churn rate 0.069
base rate 0.194
threshold 0.5: flagged 0, accuracy 0.813, recall 0.000
threshold 0.3: flagged 208, accuracy 0.799, recall 0.519
ValueError: threshold must be in [0, 1], got 1.5

How it works:

  1. State moved into the object: the counts of the procedural version become the learned attributes rates_ and base_rate_, set only by fit. The fitted check is hasattr(self, "rates_").
  2. One grouping rule: the static method _group is used by both fit and predict_proba, so training and prediction can never group rows differently.
  3. Hyperparameter vs learned attribute: threshold is a setting of the model. __init__ stores it unchanged, and _validate_params() checks it where it is used, as scikit-learn does. So model.threshold = 1.5 is accepted, and the error comes at predict. Changing the threshold does not require a new fit, because the rates do not depend on it.
  4. Train/test split: the model learns on 4,000 customers and is judged on 1,000 others, so the scores are not inflated by memorized rows.
  5. The result: the highest group rate is about 0.47 (new month-to-month customers), below 0.5. So threshold 0.5 flags nobody. Its accuracy equals the share of loyal customers, the score of the trivial “nobody churns” rule. Threshold 0.3 trades a little accuracy for real recall. Module 36 chooses thresholds properly with precision, recall and cost.

Alternative: add more columns to the group, such as logins_last_30d <= 3, and fall back to base_rate_ for small groups. Better still, use logistic regression (module 36), which combines many features without splitting the data into ever smaller groups.

M18-X03 · Parse HTTP requests into objects

Section titled “M18-X03 · Parse HTTP requests into objects”
Challenge

Outside data science, every web framework turns the raw text of an HTTP request into an object. Build a small HttpRequest class.

  • __init__(method, path, query, headers, body) stores clean values. method is a validated property: one of GET, POST, PUT, PATCH, DELETE, stored in upper case.
  • A class method from_raw(raw) parses the request text: the request line (METHOD target HTTP/1.1), the header lines up to the first empty line, and the body after it. Lines end with \r\n. The target "/api/products?page=2&per_page=10" splits into the path and a query dict of strings.
  • Header names are case-insensitive: store them in lower case, and add a method header(name, default=None).
  • Properties: is_json (the Content-Type starts with application/json) and json (the parsed body, or None when the request is not JSON).

Parse the two requests in the starter and print what an API endpoint would read from them.

Expected output
GET /api/products {'page': '2', 'per_page': '10'}
page: 2 | request id: 7f3a
is JSON: False | body: None
POST /api/predict application/json; charset=utf-8
C03991 6 2
rejected: unsupported HTTP method 'FETCH'
Starter
import json
get_raw = (
"GET /api/products?page=2&per_page=10 HTTP/1.1\r\n"
"Host: shop.example.com\r\n"
"Accept: application/json\r\n"
"X-Request-ID: 7f3a\r\n"
"\r\n"
)
post_raw = (
"post /api/predict HTTP/1.1\r\n"
"Host: ml.example.com\r\n"
"Content-Type: application/json; charset=utf-8\r\n"
"\r\n"
'{"customer_id": "C03991", "tenure_months": 6, "logins_last_30d": 2}'
)
class HttpRequest:
# TODO: __init__, the method property, from_raw, header, is_json, json
...
# TODO: parse both requests and print their method, path, query, a header and the JSON
# TODO: show that HttpRequest("FETCH", "/", {}, {}, "") is rejected
Hint 1

raw.split("\r\n\r\n", 1) separates the head from the body. head.split("\r\n") gives the request line first, then one header per line.

Hint 2

target.partition("?") gives the path, the "?" and the query text. Each key=value pair of the query text splits with pair.split("=", 1). A header line splits with line.split(":", 1); strip the spaces.

Hint 3

json is a property that returns json.loads(self.body) if self.is_json else None. Inside the class, the module json and the property json do not clash, because the property is reached only through self.json.

Solution
import json
from typing import Self
get_raw = (
"GET /api/products?page=2&per_page=10 HTTP/1.1\r\n"
"Host: shop.example.com\r\n"
"Accept: application/json\r\n"
"X-Request-ID: 7f3a\r\n"
"\r\n"
)
post_raw = (
"post /api/predict HTTP/1.1\r\n"
"Host: ml.example.com\r\n"
"Content-Type: application/json; charset=utf-8\r\n"
"\r\n"
'{"customer_id": "C03991", "tenure_months": 6, "logins_last_30d": 2}'
)
class HttpRequest:
allowed_methods = ("GET", "POST", "PUT", "PATCH", "DELETE")
def __init__(
self,
method: str,
path: str,
query: dict[str, str],
headers: dict[str, str],
body: str,
):
self.method = method # validated by the property
self.path = path
self.query = query
self._headers = {name.lower(): value for name, value in headers.items()}
self.body = body
@property
def method(self) -> str:
return self._method
@method.setter
def method(self, value: str) -> None:
if value.upper() not in self.allowed_methods:
raise ValueError(f"unsupported HTTP method {value!r}")
self._method = value.upper()
@staticmethod
def _parse_query(text: str) -> dict[str, str]:
pairs = (item.split("=", 1) for item in text.split("&") if item)
return {key: value for key, value in pairs}
@classmethod
def from_raw(cls, raw: str) -> Self:
head, _, body = raw.partition("\r\n\r\n")
request_line, *header_lines = head.split("\r\n")
method, target, _version = request_line.split(" ")
path, _, query_text = target.partition("?")
headers = {}
for line in header_lines:
name, value = line.split(":", 1)
headers[name.strip()] = value.strip()
return cls(method, path, cls._parse_query(query_text), headers, body)
def header(self, name: str, default: str | None = None) -> str | None:
return self._headers.get(name.lower(), default)
@property
def is_json(self) -> bool:
return self.header("content-type", "").startswith("application/json")
@property
def json(self) -> dict | None:
return json.loads(self.body) if self.is_json else None
get_req = HttpRequest.from_raw(get_raw)
print(get_req.method, get_req.path, get_req.query)
page = int(get_req.query.get("page", "1"))
print("page:", page, "| request id:", get_req.header("x-request-id"))
print("is JSON:", get_req.is_json, "| body:", get_req.json)
post_req = HttpRequest.from_raw(post_raw)
print(post_req.method, post_req.path, post_req.header("CONTENT-TYPE"))
features = post_req.json
print(features["customer_id"], features["tenure_months"], features["logins_last_30d"])
try:
HttpRequest("FETCH", "/", {}, {}, "")
except ValueError as exc:
print("rejected:", exc)
assert get_req.query == {"page": "2", "per_page": "10"}
assert post_req.method == "POST" and post_req.is_json
assert get_req.header("Missing", "none") == "none"
Output
GET /api/products {'page': '2', 'per_page': '10'}
page: 2 | request id: 7f3a
is JSON: False | body: None
POST /api/predict application/json; charset=utf-8
C03991 6 2
rejected: unsupported HTTP method 'FETCH'

How it works:

  1. from_raw does the parsing and __init__ takes clean values. A test can build a request directly, as the rejected FETCH call does, without writing raw text.
  2. partition("\r\n\r\n") cuts the text at the first empty line: before it is the head, after it the body. request_line, *header_lines = ... is star-unpacking (module 04).
  3. Header names are stored in lower case, and header() lowercases the name it looks up. So CONTENT-TYPE, Content-Type and content-type find the same value, as HTTP requires.
  4. The method property normalizes post to POST and rejects unknown methods, at creation and on every later assignment.
  5. json reads like data but is computed from body. An endpoint of a prediction API reads the customer features from it; module 44 does this with FastAPI.

Alternative: the standard library parses the query string with urllib.parse.parse_qs("page=2&per_page=10"). It returns lists ({'page': ['2'], ...}), because a key can repeat in a URL. Real frameworks (Starlette, Flask, Django) use their own request classes with the same ideas: properties, case-insensitive headers and lazy body parsing.

M18-X04 · Early stopping for a training loop

Section titled “M18-X04 · Early stopping for a training loop”
Challenge

Training loops often stop when the validation loss (the error on data the model does not train on) stops improving. Write an EarlyStopping class, as PyTorch and Keras users write them.

  • Validated properties: patience (an int ≥ 1: how many epochs without improvement are allowed) and min_delta (a number ≥ 0: the smallest drop that counts as an improvement). A wrong type raises TypeError; a value out of range raises ValueError.
  • step(val_loss) -> bool is called once per epoch. It counts epochs from 1. When the loss is lower than best_loss_ - min_delta, it stores the new best_loss_ and best_epoch_ and resets an internal counter. Otherwise it increases the counter. It returns True when the counter reaches patience.
  • A property stopped_epoch returns the epoch at which step first returned True, or None.
  • reset() clears the state, so the object can watch a second run.

Run it on the two validation-loss logs in the starter, with patience=3, min_delta=0.005. Then run log A again with patience=5 on the same object after reset().

Expected output
patience=3: stop at epoch 7, best epoch 4 (loss 0.581)
patience=3: no early stop, best epoch 10 (loss 0.52)
patience=5: no early stop, best epoch 9 (loss 0.574)
rejected: patience must be an int >= 1, got 0
Starter
log_a = [0.92, 0.71, 0.60, 0.581, 0.578, 0.576, 0.590, 0.602, 0.574, 0.571, 0.640]
log_b = [1.10, 0.95, 0.83, 0.74, 0.67, 0.62, 0.58, 0.55, 0.53, 0.52]
class EarlyStopping:
def __init__(self, patience: int = 3, min_delta: float = 0.0):
self.patience = patience
self.min_delta = min_delta
self.reset()
# TODO: validated properties patience and min_delta
# TODO: reset(), step(val_loss) -> bool and the property stopped_epoch
def run(stopper: EarlyStopping, losses: list[float]) -> None:
# TODO: call step() for each loss and stop the loop when it returns True
# TODO: print the stop epoch (or "no early stop"), the best epoch and the best loss
...
Hint 1

reset() sets self.best_loss_ = math.inf, self.best_epoch_ = 0, self._epoch = 0, self._bad_epochs = 0 and self._stopped_epoch = None. math.inf is larger than every loss, so the first loss is always an improvement.

Hint 2

For log A with min_delta=0.005: 0.578 is not lower than 0.581 − 0.005 = 0.576. So epoch 5 does not count as an improvement, although the loss went down.

Solution
import math
log_a = [0.92, 0.71, 0.60, 0.581, 0.578, 0.576, 0.590, 0.602, 0.574, 0.571, 0.640]
log_b = [1.10, 0.95, 0.83, 0.74, 0.67, 0.62, 0.58, 0.55, 0.53, 0.52]
class EarlyStopping:
def __init__(self, patience: int = 3, min_delta: float = 0.0):
self.patience = patience
self.min_delta = min_delta
self.reset()
@property
def patience(self) -> int:
return self._patience
@patience.setter
def patience(self, value: int) -> None:
if isinstance(value, bool) or not isinstance(value, int):
raise TypeError(f"patience must be an int, got {type(value).__name__}")
if value < 1:
raise ValueError(f"patience must be an int >= 1, got {value!r}")
self._patience = value
@property
def min_delta(self) -> float:
return self._min_delta
@min_delta.setter
def min_delta(self, value: float) -> None:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError(f"min_delta must be a number, got {type(value).__name__}")
if value < 0:
raise ValueError(f"min_delta must be a number >= 0, got {value!r}")
self._min_delta = value
def reset(self) -> None:
self.best_loss_ = math.inf
self.best_epoch_ = 0
self._epoch = 0
self._bad_epochs = 0
self._stopped_epoch: int | None = None
def step(self, val_loss: float) -> bool:
self._epoch += 1
if val_loss < self.best_loss_ - self.min_delta:
self.best_loss_ = val_loss
self.best_epoch_ = self._epoch
self._bad_epochs = 0
else:
self._bad_epochs += 1
if self._bad_epochs >= self.patience and self._stopped_epoch is None:
self._stopped_epoch = self._epoch
return self._stopped_epoch is not None
@property
def stopped_epoch(self) -> int | None:
return self._stopped_epoch
def run(stopper: EarlyStopping, losses: list[float]) -> None:
for loss in losses:
if stopper.step(loss):
break
stop = stopper.stopped_epoch
when = f"stop at epoch {stop}" if stop else "no early stop"
print(f"patience={stopper.patience}: {when}, "
f"best epoch {stopper.best_epoch_} (loss {stopper.best_loss_})")
stopper = EarlyStopping(patience=3, min_delta=0.005)
run(stopper, log_a)
stopper.reset()
run(stopper, log_b)
stopper.reset()
stopper.patience = 5
run(stopper, log_a)
try:
stopper.patience = 0
except ValueError as exc:
print("rejected:", exc)
assert stopper.patience == 5
check = EarlyStopping(patience=3, min_delta=0.005)
assert [check.step(x) for x in log_a[:7]] == [False] * 6 + [True]
Output
patience=3: stop at epoch 7, best epoch 4 (loss 0.581)
patience=3: no early stop, best epoch 10 (loss 0.52)
patience=5: no early stop, best epoch 9 (loss 0.574)
rejected: patience must be an int >= 1, got 0

How it works:

  1. Log A, patience 3: the best loss is 0.581 at epoch 4. Epochs 5, 6 and 7 are not better by at least 0.005, so the counter reaches 3 at epoch 7 and training stops.
  2. Log B: the loss keeps dropping by more than 0.005, so the counter never reaches 3. The best epoch is the last one.
  3. Log A, patience 5: after reset(), the same object watches a new run. Epoch 9 (0.574) beats 0.581 by 0.007, so the counter restarts. Epoch 10 (0.571) is lower, but by less than 0.005, so it does not count. The log ends before the counter reaches 5, so there is no early stop, and the best epoch is 9. More patience found a better model than the stop at epoch 7.
  4. Encapsulation: the epoch and bad-epoch counters are internal (_epoch, _bad_epochs), the results that callers read end with _, and the settings are validated properties. A training loop needs only step().
  5. The last assert replays the first 7 epochs and checks the exact sequence of decisions.

Alternative: PyTorch Lightning and Keras ship an EarlyStopping callback with the same settings (patience, min_delta). Most also restore the weights of the best epoch, which you would store in step() next to best_loss_ (module 42).

Challenge

Fix the bugs: a small registry lets a script create models by name, a pattern you build fully in module 22. The code has five bugs. One class attribute looks suspicious but is correct: find it and explain in a comment why it must stay shared. The data are the first 8 house prices of data/houses.csv, in thousands of USD. When the script works, add one more call: ModelRegistry.create("knn"), and print the KeyError it raises for this unknown name.

Expected output
[540.0, 540.0, 540.0]
learned mean: 560.0
models created: 1
KeyError: "unknown model 'knn'; known: ['mean']"
Starter
class ModelRegistry:
_factories = {} # name -> class
def register(cls, name, factory):
if name in cls._factories:
raise ValueError(f"model {name!r} is already registered")
cls._factories[name] = factory
@classmethod
def create(cls, name, **params):
if name not in cls._factories:
raise KeyError(f"unknown model {name!r}; known: {sorted(cls._factories)}")
return cls._factories[name](**params)
class MeanRegressor:
created = 0
def __init__(self, shift=0.0):
self.shift = shift # stored unchanged, scikit-learn style
self.created += 1
def fit(self, y):
self.__mean = sum(y) / len(y)
@staticmethod
def predict(self, n):
return [round(self.__mean + self.shift, 1)] * n
ModelRegistry.register("mean", MeanRegressor)
prices = [1097.5, 486.5, 223.0, 431.0, 1080.0, 327.5, 455.0, 379.5]
model = ModelRegistry.create("mean", shift=-20.0).fit(prices)
print(model.predict(3))
print("learned mean:", round(model.__mean, 1))
print("models created:", MeanRegressor.created)
# TODO: fix the five bugs; keep the correct class attribute and explain why
# TODO: then call ModelRegistry.create("knn") and print "KeyError:" and the error
Hint 1

Fix one error at a time: run, read the last traceback line, fix, run again. The first error appears at the line ModelRegistry.register("mean", MeanRegressor).

Hint 2

Look for: two wrong or missing decorators, a counter that never counts, a method that must return self, and a name that Python renames inside the class.

Hint 3

A registry must be the same for the whole program. If _factories were created per instance, which instance would hold the registered models? The registry is never instantiated at all.

Solution
from typing import Self
class ModelRegistry:
# Correct as a class attribute: the registry is shared on purpose. Every
# caller must see the same name -> class mapping, and nobody creates
# ModelRegistry instances; all methods are class methods.
_factories: dict[str, type] = {}
@classmethod # bug 1: without it, "mean" was passed as cls
def register(cls, name: str, factory: type) -> None:
if name in cls._factories:
raise ValueError(f"model {name!r} is already registered")
cls._factories[name] = factory
@classmethod
def create(cls, name: str, **params):
if name not in cls._factories:
raise KeyError(f"unknown model {name!r}; known: {sorted(cls._factories)}")
return cls._factories[name](**params)
class MeanRegressor:
created = 0
def __init__(self, shift: float = 0.0):
self.shift = shift # stored unchanged, scikit-learn style
MeanRegressor.created += 1 # bug 2: self.created += 1 never counted
def fit(self, y: list[float]) -> Self:
self.mean_ = sum(y) / len(y) # bug 5: a public learned attribute, not __mean
return self # bug 4: fit must return self
def predict(self, n: int) -> list[float]: # bug 3: no @staticmethod
return [round(self.mean_ + self.shift, 1)] * n
ModelRegistry.register("mean", MeanRegressor)
prices = [1097.5, 486.5, 223.0, 431.0, 1080.0, 327.5, 455.0, 379.5]
model = ModelRegistry.create("mean", shift=-20.0).fit(prices)
print(model.predict(3))
print("learned mean:", round(model.mean_, 1))
print("models created:", MeanRegressor.created)
try:
ModelRegistry.create("knn")
except KeyError as exc:
print("KeyError:", exc)
assert isinstance(model, MeanRegressor) and model.shift == -20.0
assert MeanRegressor.created == 1
assert "_factories" not in vars(MeanRegressor)
Output
[540.0, 540.0, 540.0]
learned mean: 560.0
models created: 1
KeyError: "unknown model 'knn'; known: ['mean']"

How it works:

  1. Bug 1, the missing @classmethod: ModelRegistry.register("mean", MeanRegressor) called a plain function with cls="mean" and name=MeanRegressor, and no factory. The run failed with TypeError: ModelRegistry.register() missing 1 required positional argument: 'factory'.
  2. Bug 4, fit returned None: so .fit(prices) gave None, and model.predict(3) raised AttributeError: 'NoneType' object has no attribute 'predict'. fit must end with return self. (This error comes second when you fix the bugs in the order they appear.)
  3. Bug 3, the wrong @staticmethod: a static method receives no instance, so model.predict(3) passed 3 as self and nothing as n: TypeError: MeanRegressor.predict() missing 1 required positional argument: 'n'. predict reads the state of the model, so it is an instance method.
  4. Bug 5, the mangled name: inside the class, self.__mean was renamed to self._MeanRegressor__mean. Outside the class, model.__mean is not renamed, so it raised AttributeError: 'MeanRegressor' object has no attribute '__mean'. The fix stores the scikit-learn style learned attribute mean_, which is public on purpose.
  5. Bug 2, the counter: this bug raises nothing; the script just prints models created: 0. self.created += 1 created an instance attribute, and the class counter stayed at 0. MeanRegressor.created += 1 changes the shared value.
  6. The correct class attribute: _factories is shared state by design. A mutable class attribute is a bug only when each instance needs its own copy.

Alternative: a module-level dict FACTORIES = {} and two functions register() and create() do the same job without a class. Module 22 turns the registry into a decorator: @register("mean") above the class definition.