---
title: Problem set 5
heading: "Problem set 5: modules and classes"
eyebrow: A4 · Problem set 5
type: problems
---

::: hook
These labs use lessons 19 to 21: the standard library's modules, classes of your own, and state machines. Each one wraps an engineering idea (a resistor with a tolerance, a battery that drains, a filter) in a class, so the code that uses it reads like the circuit. When a check fails, the hidden test's message says which case went wrong.
:::

::: pool
pick: 5

::: check
kind: python
given: R = 100 | 1000 | 4700; t = 1 | 5; P = 0.25 | 0.5; V = 3 | 5 | 12

## Write a class `Resistor` with attributes `ohms`, `tol` (percent) and `rating` (watts), and methods `limits()` returning `(lowest, highest)` values, `power(v)` returning the power at voltage `v` using the nominal value, and `safe(v)` returning `True` if the power is at most half the rating, at the lowest value (the worst case). Set `r = Resistor(R, t, P)` for {R} Ω, {t}%, {P} W, and `ok = r.safe(V)` at {V} V.

```python starter
class Resistor:
    def __init__(self, ohms, tol, rating):
        self.ohms = ohms

    def limits(self):
        return self.ohms, self.ohms

    def power(self, v):
        return 0

    def safe(self, v):
        return True

r = Resistor(R, t, P)
ok = r.safe(V)
print(r.limits(), r.power(V), ok)
```

```python solution
class Resistor:
    def __init__(self, ohms, tol, rating):
        self.ohms = ohms
        self.tol = tol
        self.rating = rating

    def limits(self):
        d = self.ohms * self.tol / 100
        return self.ohms - d, self.ohms + d

    def power(self, v):
        return v * v / self.ohms

    def safe(self, v):
        return v * v / self.limits()[0] <= self.rating / 2

r = Resistor(R, t, P)
ok = r.safe(V)
print(r.limits(), r.power(V), ok)
```

```python tests
import math
x = Resistor(1000, 5, 0.25)
lo, hi = x.limits()
assert math.isclose(lo, 950) and math.isclose(hi, 1050), f"1 kohm at 5% runs from 950 to 1050 ohms; got {(lo, hi)}."
assert math.isclose(x.power(10), 0.1), "10 V across 1 kohm is 0.1 W."
assert x.safe(10) is True and x.safe(12) is False, "At 12 V the 950 ohm worst case takes 0.152 W, over half of 0.25 W."
assert ok == (V * V / (R * (1 - t / 100)) <= P / 2), "ok doesn't match this lab's resistor and voltage."
```
:::

::: check
kind: python
given: C = 1000 | 2500; I = 50 | 120; h = 3 | 6

## Write a class `Battery(capacity_mAh)` that starts full. `draw(mA, hours)` uses up that much charge (never below zero), `percent()` returns the charge left as a percentage of capacity, and `hours_left(mA)` how long it could still supply `mA`. Set `b = Battery(C)`, call `b.draw(I, h)`, and set `left = b.percent()` and `more = b.hours_left(I)` for {C} mAh, {I} mA and {h} hours.

```python starter
class Battery:
    def __init__(self, capacity_mAh):
        self.capacity = capacity_mAh

    def draw(self, mA, hours):
        pass

    def percent(self):
        return 100

    def hours_left(self, mA):
        return 0

b = Battery(C)
b.draw(I, h)
left = b.percent()
more = b.hours_left(I)
print(left, more)
```

```python solution
class Battery:
    def __init__(self, capacity_mAh):
        self.capacity = capacity_mAh
        self.charge = capacity_mAh

    def draw(self, mA, hours):
        self.charge = max(0, self.charge - mA * hours)

    def percent(self):
        return 100 * self.charge / self.capacity

    def hours_left(self, mA):
        return self.charge / mA

b = Battery(C)
b.draw(I, h)
left = b.percent()
more = b.hours_left(I)
print(left, more)
```

```python tests
import math
x = Battery(1000)
x.draw(100, 2)
assert math.isclose(x.percent(), 80) and math.isclose(x.hours_left(100), 8), "After 100 mA for 2 h, a 1000 mAh battery is at 80% with 8 h left at 100 mA."
x.draw(500, 10)
assert x.percent() == 0 and x.hours_left(10) == 0, "Charge never goes below zero."
y = Battery(500)
assert y.percent() == 100, "A new battery starts full."
used = min(C, I * h)
assert math.isclose(left, 100 * (C - used) / C) and math.isclose(more, (C - used) / I), "left and more don't match this lab's values."
```
:::

::: check
kind: python
given: a = 3 | 5; p = 30 | 120; b = 2 | 4; q = -45 | 60

## Write a class `Phasor(mag, deg)` that stores a complex value, with `__add__` and `__mul__` returning new `Phasor`s, and properties `mag` and `deg` (the angle in degrees). Set `s = Phasor(a, p) + Phasor(b, q)` and `m = Phasor(a, p) * Phasor(b, q)` for {a}∠{p}° and {b}∠{q}°.

```python starter
import cmath, math

class Phasor:
    def __init__(self, mag, deg):
        self.z = complex(mag, deg)

    def __add__(self, other):
        return self

    def __mul__(self, other):
        return self

    @property
    def mag(self):
        return self.z.real

    @property
    def deg(self):
        return self.z.imag

s = Phasor(a, p) + Phasor(b, q)
m = Phasor(a, p) * Phasor(b, q)
print(s.mag, s.deg, m.mag, m.deg)
```

```python solution
import cmath, math

class Phasor:
    def __init__(self, mag, deg):
        self.z = cmath.rect(mag, math.radians(deg))

    @classmethod
    def from_complex(cls, z):
        out = cls(0, 0)
        out.z = z
        return out

    def __add__(self, other):
        return Phasor.from_complex(self.z + other.z)

    def __mul__(self, other):
        return Phasor.from_complex(self.z * other.z)

    @property
    def mag(self):
        return abs(self.z)

    @property
    def deg(self):
        return math.degrees(cmath.phase(self.z))

s = Phasor(a, p) + Phasor(b, q)
m = Phasor(a, p) * Phasor(b, q)
print(s.mag, s.deg, m.mag, m.deg)
```

```python tests
import math
t = Phasor(3, 0) + Phasor(4, 90)
assert math.isclose(t.mag, 5) and math.isclose(t.deg, 53.130102354), f"3∠0 + 4∠90 is 5∠53.13; got {t.mag}∠{t.deg}."
u = Phasor(2, 30) * Phasor(3, 45)
assert math.isclose(u.mag, 6) and math.isclose(u.deg, 75), "Multiplying multiplies lengths and adds angles: 6∠75."
assert isinstance(t, Phasor) and isinstance(u, Phasor), "+ and * should return Phasor objects."
assert math.isclose(m.mag, a * b), "m's length should be the product of the lengths."
```
:::

::: check
kind: python
given: a = 3 | 6 | 10; b = 4 | 12 | 15; c = 5 | 20 | 30

## Using the `fractions` module, write `parallel(*rs)` returning the exact parallel combination of any number of resistances. Set `R = parallel(Fraction(a), Fraction(b), Fraction(c))` for {a}, {b} and {c} Ω, and `top` and `bottom` to its numerator and denominator in lowest terms.

```python starter
from fractions import Fraction

def parallel(*rs):
    return sum(rs)

R = parallel(Fraction(a), Fraction(b), Fraction(c))
top, bottom = 0, 1
print(R, top, bottom)
```

```python solution
from fractions import Fraction

def parallel(*rs):
    return 1 / sum(1 / r for r in rs)

R = parallel(Fraction(a), Fraction(b), Fraction(c))
top, bottom = R.numerator, R.denominator
print(R, top, bottom)
```

```python tests
from fractions import Fraction
assert parallel(Fraction(3), Fraction(6)) == 2, "3 and 6 ohms in parallel make exactly 2 ohms."
assert parallel(Fraction(10), Fraction(15), Fraction(30)) == 5, "10, 15 and 30 ohms make exactly 5 ohms."
assert parallel(Fraction(4), Fraction(5)) == Fraction(20, 9), "4 and 5 ohms make 20/9 ohms, kept exact."
assert Fraction(top, bottom) == 1 / (Fraction(1, a) + Fraction(1, b) + Fraction(1, c)), "top and bottom don't match this lab's resistors."
```
:::

::: check
kind: python
given: f1 = 100 | 300; f2 = 5000 | 20000; f = 1000 | 2000

## Write a base class `Filter` whose `gain(f)` returns the magnitude of its complex `H(f)`, with subclasses `LowPass(fc)` and `HighPass(fc)` that define `H(f)` for first-order RC filters. Then write `cascade(filters, f)` returning the product of their gains. Set `g = cascade([HighPass(f1), LowPass(f2)], f)` for a band-pass from {f1} Hz to {f2} Hz, at {f} Hz.

```python starter
class Filter:
    def gain(self, f):
        return 1

class LowPass(Filter):
    def __init__(self, fc):
        self.fc = fc

class HighPass(Filter):
    def __init__(self, fc):
        self.fc = fc

def cascade(filters, f):
    return 1

g = cascade([HighPass(f1), LowPass(f2)], f)
print(g)
```

```python solution
class Filter:
    def gain(self, f):
        return abs(self.H(f))

class LowPass(Filter):
    def __init__(self, fc):
        self.fc = fc

    def H(self, f):
        return 1 / (1 + 1j * f / self.fc)

class HighPass(Filter):
    def __init__(self, fc):
        self.fc = fc

    def H(self, f):
        return (1j * f / self.fc) / (1 + 1j * f / self.fc)

def cascade(filters, f):
    g = 1
    for flt in filters:
        g *= flt.gain(f)
    return g

g = cascade([HighPass(f1), LowPass(f2)], f)
print(g)
```

```python tests
import math
assert math.isclose(LowPass(1000).gain(1000), 1 / math.sqrt(2)), "A low-pass is down to 0.707 at its corner."
assert math.isclose(HighPass(1000).gain(1000), 1 / math.sqrt(2)) and HighPass(1000).gain(10) < 0.011, "A high-pass is 0.707 at its corner and small far below it."
assert math.isclose(cascade([LowPass(1000), LowPass(1000)], 1000), 0.5), "Two stages at their corner give 0.707 squared."
x = f / f1
want = x / math.sqrt(1 + x * x) / math.sqrt(1 + (f / f2) ** 2)
assert math.isclose(g, want), f"g should be {want:.4f} for this band-pass at {f} Hz; got {g}."
```
:::

::: check
kind: python
given: T = 15 | 25 | 40

## Write a base class `Sensor` with `read()` returning `self.convert(self.raw)`, and a subclass `Thermistor(R0, B)` whose `convert(R)` turns a resistance in ohms into °C by $\frac1T = \frac{1}{T_0} + \frac{1}{B}\ln\frac{R}{R_0}$, with $T_0$ = 298.15 K. Set `th = Thermistor(10000, 3950)`, set `th.raw` to the resistance it shows at {T} °C (from the inverse formula, `R = R0 * exp(B * (1/T - 1/T0))` with `T` in kelvin), and `t = th.read()`.

```python starter
import math

class Sensor:
    raw = 0

    def read(self):
        return self.raw

class Thermistor(Sensor):
    def __init__(self, R0, B):
        self.R0, self.B = R0, B

th = Thermistor(10000, 3950)
th.raw = 10000
t = th.read()
print(t)
```

```python solution
import math

class Sensor:
    raw = 0

    def read(self):
        return self.convert(self.raw)

class Thermistor(Sensor):
    def __init__(self, R0, B):
        self.R0, self.B = R0, B

    def convert(self, R):
        T0 = 298.15
        return 1 / (1 / T0 + math.log(R / self.R0) / self.B) - 273.15

th = Thermistor(10000, 3950)
th.raw = 10000 * math.exp(3950 * (1 / (T + 273.15) - 1 / 298.15))
t = th.read()
print(t)
```

```python tests
import math
x = Thermistor(10000, 3950)
x.raw = 10000
assert math.isclose(x.read(), 25, abs_tol=1e-9), "At R0 the thermistor reads 25 C."
x.raw = 5000
assert math.isclose(x.read(), 41.46, abs_tol=0.01), f"At 5 kohm it reads 41.46 C; got {x.read()}."
assert math.isclose(t, T, abs_tol=1e-9), f"Converting the resistance at {T} C should give back {T} C; got {t}."
```
:::

::: check
kind: python
given: k = 2 | 3

## Using `dataclasses`, write a `Measurement` dataclass with fields `name`, `value` and `unit`, and a method `line()` returning `"name: value unit"` with the value to three significant figures (`:.3g`). Set `ms` to the starter's readings as `Measurement`s sorted by value, largest first, and `text` to the `line()` of the first `k` = {k}, joined by newlines.

```python starter
from dataclasses import dataclass

readings = [("TP1", 4.9732, "V"), ("TP2", 3.30491, "V"), ("TP3", 12.0874, "V"), ("TP4", 0.81234, "V")]

ms = []
text = ""
print(text)
```

```python solution
from dataclasses import dataclass

readings = [("TP1", 4.9732, "V"), ("TP2", 3.30491, "V"), ("TP3", 12.0874, "V"), ("TP4", 0.81234, "V")]

@dataclass
class Measurement:
    name: str
    value: float
    unit: str

    def line(self):
        return f"{self.name}: {self.value:.3g} {self.unit}"

ms = sorted((Measurement(*r) for r in readings), key=lambda m: m.value, reverse=True)
text = "\n".join(m.line() for m in ms[:k])
print(text)
```

```python tests
assert [m.name for m in ms] == ["TP3", "TP1", "TP2", "TP4"], f"Sorted largest first: TP3, TP1, TP2, TP4; got {[m.name for m in ms]}."
assert ms[0].line() == "TP3: 12.1 V" and ms[3].line() == "TP4: 0.812 V", f"Three significant figures: '12.1 V' and '0.812 V'; got {ms[0].line()!r}, {ms[3].line()!r}."
assert text == "\n".join(["TP3: 12.1 V", "TP1: 4.97 V", "TP2: 3.3 V"][:k]), f"text should be the first k lines; got {text!r}."
```
:::

::: check
kind: python
given: m = 3 | 5 | 8; k = 1..5 int

## A digital line is sampled at a steady rate. A real pulse is a run of at least `m` = {m} high samples between lows; shorter high runs are noise. Write a class `PulseCounter(m)` whose `step(x)` takes one sample and returns `True` at the low sample that ends a real pulse. Set `count` to the number of real pulses in the starter's samples, and `widths` to the list of their lengths in samples.

```python starter
import random
random.seed(k)
x = []
for _ in range(12):
    x += [0] * random.randint(2, 6) + [1] * random.choice([1, 2, m - 1, m, m + 3, 2 * m])
x += [0, 0]

class PulseCounter:
    def __init__(self, m):
        self.m = m
        self.prev = 0
    def step(self, s):
        ended = self.prev == 1 and s == 0
        self.prev = s
        return ended

pc = PulseCounter(m)
count = sum(pc.step(s) for s in x)
widths = []
print(count, widths)
```

```python solution
import random
random.seed(k)
x = []
for _ in range(12):
    x += [0] * random.randint(2, 6) + [1] * random.choice([1, 2, m - 1, m, m + 3, 2 * m])
x += [0, 0]

class PulseCounter:
    def __init__(self, m):
        self.m, self.run, self.widths = m, 0, []
    def step(self, s):
        if s:
            self.run += 1
            return False
        done = self.run >= self.m
        if done:
            self.widths.append(self.run)
        self.run = 0
        return done

pc = PulseCounter(m)
count = sum(pc.step(s) for s in x)
widths = pc.widths
print(count, widths)
```

```python tests
runs, r = [], 0
for s in x:
    if s: r += 1
    else:
        if r: runs.append(r)
        r = 0
real = [w for w in runs if w >= m]
assert count == len(real), f"There are {len(real)} high runs of at least {m} samples."
assert widths == real, f"The real pulses' widths, in order, are {real}."
```

::: right
Right. The machine's state is the length of the current high run; a low sample ends the run and decides, by its length, whether it was a pulse. Glitches never reach the threshold.
:::
:::
:::
