---
title: Problem set 6
heading: "Problem set 6: program structure"
eyebrow: A4 · Problem set 6
type: problems
---

::: hook
These labs use lessons 19 to 25: the standard library, classes, state machines, recursion and searching, running time, and sorting. They're closer to real tools: an impedance sweep, a component model, a solver, a Monte Carlo check.
:::

::: pool
pick: 5

::: check
kind: python
given: R = 10 | 50; L = 1 | 10; C = 0.1 | 1

## For a series RLC with `R` = {R} Ω, `L` = {L} mH and `C` = {C} µF, set `Z` to a list of complex impedances at the frequencies in `fs`, and `fmin` to the frequency in `fs` where $|Z|$ is smallest.

```python starter
import math, cmath
fs = [100 * 1.1**k for k in range(80)]
Z = []
fmin = None
print(fmin)
```

```python solution
import math, cmath
fs = [100 * 1.1**k for k in range(80)]
Z = [R + 1j * 2 * math.pi * f * L * 1e-3 + 1 / (1j * 2 * math.pi * f * C * 1e-6) for f in fs]
fmin = min(zip(fs, Z), key=lambda p: abs(p[1]))[0]
print(fmin)
```

```python tests
import math
fs = [100 * 1.1**k for k in range(80)]
assert len(Z) == 80 and all(isinstance(z, complex) for z in Z), "Z should be 80 complex impedances, one per frequency."
z0 = R + 1j * 2 * math.pi * fs[5] * L * 1e-3 + 1 / (1j * 2 * math.pi * fs[5] * C * 1e-6)
assert abs(Z[5] - z0) < 1e-9 * abs(z0), "Z = R + jωL + 1/(jωC), with L in mH and C in µF."
f0 = 1 / (2 * math.pi * math.sqrt(L * 1e-3 * C * 1e-6))
assert abs(math.log(fmin / f0)) < math.log(1.1), "fmin should be the sweep point nearest the resonance 1/(2π√(LC))."
```
:::

::: check
kind: python
given: C = 1 | 10 | 100; esr = 0.01 | 0.1; f = 1000 | 100000

## Write a class `Capacitor` with attributes `C` (farads) and `esr` (ohms) and a method `impedance(f)` returning the complex $\text{ESR} + 1/(j\omega C)$. Set `z = Capacitor(C * 1e-6, esr).impedance(f)` and `mag = abs(z)`.

```python starter
class Capacitor:
    pass

z = 0
mag = 0
print(z, mag)
```

```python solution
import math

class Capacitor:
    def __init__(self, C, esr):
        self.C = C
        self.esr = esr

    def impedance(self, f):
        return self.esr + 1 / (1j * 2 * math.pi * f * self.C)

z = Capacitor(C * 1e-6, esr).impedance(f)
mag = abs(z)
print(z, mag)
```

```python tests
import math
w = 2 * math.pi * f
want = esr + 1 / (1j * w * C * 1e-6)
assert abs(z - want) < 1e-12 * abs(want), "impedance should be esr + 1/(jωC)."
assert abs(mag - abs(want)) < 1e-12 * abs(want), "mag should be abs(z)."
```
:::

::: check
kind: python
given: fc = 100 | 1000 | 5000; g = 0.5 | 0.2 | 0.1

## An RC low-pass has $|H| = 1/\sqrt{1 + (f/f_c)^2}$ with `fc` = {fc} Hz. Use bisection between `fc` and `1000 * fc` to set `f` to the frequency where $|H|$ = `g` = {g}, to within 1e-9 relative.

```python starter
f = fc
print(f)
```

```python solution
def H(f):
    return 1 / (1 + (f / fc)**2) ** 0.5

lo, hi = fc, 1000 * fc
while hi - lo > 1e-12 * hi:
    m = (lo + hi) / 2
    if H(m) > g:
        lo = m
    else:
        hi = m
f = (lo + hi) / 2
print(f)
```

```python tests
want = fc * (1 / g**2 - 1) ** 0.5
assert abs(f - want) < 1e-8 * want, f"f should be about {want:.6g} Hz. Bisect on H(f) − g, which falls as f rises."
```
:::

::: check
kind: python
given: k = 0..3 int; vref = 2.5 | 5

## An R-2R DAC adds `vref/2` for its first bit, `vref/4` for the second, and so on. Write a recursive `dac(bits, vref)` for a list of 0s and 1s (most significant first), and set `v = dac(code, vref)` for the starter's `code`.

```python starter
code = [[1, 0, 1, 1], [0, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1]][k]

def dac(bits, vref):
    return 0

v = dac(code, vref)
print(v)
```

```python solution
code = [[1, 0, 1, 1], [0, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1]][k]

def dac(bits, vref):
    if not bits:
        return 0.0
    return bits[0] * vref / 2 + dac(bits[1:], vref / 2)

v = dac(code, vref)
print(v)
```

```python tests
assert abs(dac([1], 4) - 2) < 1e-12 and abs(dac([0, 1], 4) - 1) < 1e-12, "The first bit adds vref/2 and the second vref/4."
code = [[1, 0, 1, 1], [0, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1]][k]
want = sum(b * vref / 2**(i + 1) for i, b in enumerate(code))
assert abs(v - want) < 1e-12, "v doesn't match the sum of the bits' weights."
```
:::

::: check
kind: python
given: t = 1 | 5; spec = 1 | 2

## Two resistors of 10 kΩ ±`t`% each form a 50% divider. With `random.seed(1)`, draw 10,000 pairs (each resistor `10e3 * random.uniform(1 - t/100, 1 + t/100)`, top then bottom) and set `frac` to the fraction of dividers whose ratio is within ±`spec`% of 0.5.

```python starter
import random
frac = 0
print(frac)
```

```python solution
import random
random.seed(1)
good = 0
for _ in range(10000):
    top = 10e3 * random.uniform(1 - t / 100, 1 + t / 100)
    bot = 10e3 * random.uniform(1 - t / 100, 1 + t / 100)
    r = bot / (top + bot)
    if abs(r - 0.5) <= 0.5 * spec / 100:
        good += 1
frac = good / 10000
print(frac)
```

```python tests
import random
random.seed(1)
good = 0
for _ in range(10000):
    top = 10e3 * random.uniform(1 - t / 100, 1 + t / 100)
    bot = 10e3 * random.uniform(1 - t / 100, 1 + t / 100)
    if abs(bot / (top + bot) - 0.5) <= 0.5 * spec / 100:
        good += 1
assert abs(frac - good / 10000) < 1e-12, "Seed with 1, draw the top resistor then the bottom for each of 10,000 dividers, and count those within spec."
```
:::

::: check
kind: python
given: target = 1300 | 3600 | 47500 | 820000

## Using `bisect.bisect_left` on the sorted E24 list in the starter, set `best` to the E24 value nearest `target` = {target}.

```python starter
import bisect
E24 = [1.0, 1.1, 1.2, 1.3, 1.5, 1.6, 1.8, 2.0, 2.2, 2.4, 2.7, 3.0,
       3.3, 3.6, 3.9, 4.3, 4.7, 5.1, 5.6, 6.2, 6.8, 7.5, 8.2, 9.1]
vals = [m * 10**d for d in range(1, 7) for m in E24]
best = None
print(best)
```

```python solution
import bisect
E24 = [1.0, 1.1, 1.2, 1.3, 1.5, 1.6, 1.8, 2.0, 2.2, 2.4, 2.7, 3.0,
       3.3, 3.6, 3.9, 4.3, 4.7, 5.1, 5.6, 6.2, 6.8, 7.5, 8.2, 9.1]
vals = [m * 10**d for d in range(1, 7) for m in E24]
i = bisect.bisect_left(vals, target)
best = min(vals[max(i - 1, 0):i + 1], key=lambda v: abs(v - target))
print(best)
```

```python tests
E24 = [1.0, 1.1, 1.2, 1.3, 1.5, 1.6, 1.8, 2.0, 2.2, 2.4, 2.7, 3.0, 3.3, 3.6, 3.9, 4.3, 4.7, 5.1, 5.6, 6.2, 6.8, 7.5, 8.2, 9.1]
vals = [m * 10**d for d in range(1, 7) for m in E24]
d = min(abs(v - target) for v in vals)
assert best is not None and abs(abs(best - target) - d) < 1e-6, "best should be the nearest E24 value: compare the values just below and just above the insertion point."
```
:::

::: check
kind: python
given: k = 0..2 int

## Set `unique` to how many distinct readings the list holds and `repeats` to how many readings are repeats of an earlier one, in one pass with a set.

```python starter
x = [[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], [7, 7, 7, 7], [1, 2, 3, 4, 5, 6, 1]][k]
unique = repeats = 0
print(unique, repeats)
```

```python solution
x = [[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], [7, 7, 7, 7], [1, 2, 3, 4, 5, 6, 1]][k]
seen = set()
repeats = 0
for v in x:
    if v in seen:
        repeats += 1
    seen.add(v)
unique = len(seen)
print(unique, repeats)
```

```python tests
xs = [[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], [7, 7, 7, 7], [1, 2, 3, 4, 5, 6, 1]][k]
assert unique == len(set(xs)), "unique should be the number of distinct values."
assert repeats == len(xs) - len(set(xs)), "repeats should count every reading already seen."
```
:::

::: check
kind: python
given: k = 1..5 int; p = 50 | 90 | 99

## Two loggers recorded `(time, value)` pairs, each list sorted by time. Without calling `sort` or `sorted`, merge them in one pass into a single list sorted by time, taking logger A's entry first when times tie. Then set `merged` to that list, and `q` to the nearest-rank `p`th percentile ({p}) of all the values (you may sort the values for that).

```python starter
import random, math
random.seed(k)
A = sorted((round(random.uniform(0, 100), 1), round(random.gauss(5, 1), 3)) for _ in range(30))
B = sorted((round(random.uniform(0, 100), 1), round(random.gauss(5, 1), 3)) for _ in range(25))
merged = A + B
q = 0
print(merged[:5], q)
```

```python solution
import random, math
random.seed(k)
A = sorted((round(random.uniform(0, 100), 1), round(random.gauss(5, 1), 3)) for _ in range(30))
B = sorted((round(random.uniform(0, 100), 1), round(random.gauss(5, 1), 3)) for _ in range(25))
merged, i, j = [], 0, 0
while i < len(A) and j < len(B):
    if A[i][0] <= B[j][0]:
        merged.append(A[i]); i += 1
    else:
        merged.append(B[j]); j += 1
merged += A[i:] + B[j:]
vals = sorted(v for t, v in merged)
q = vals[math.ceil(p / 100 * len(vals)) - 1]
print(merged[:5], q)
```

```python tests
import math
want = sorted(A + B, key=lambda e: e[0])
assert [e[0] for e in merged] == [e[0] for e in want] and len(merged) == len(A) + len(B), "merged should hold every entry, in time order."
for x, y in zip(merged, merged[1:]):
    if x[0] == y[0] and x in B and y in A:
        assert False, "On a tie, logger A's entry comes first."
vs = sorted(v for t, v in A + B)
assert q == vs[math.ceil(p / 100 * len(vs)) - 1], f"The {p}th percentile by nearest rank is item {math.ceil(p / 100 * len(vs))} of the sorted values."
```

::: right
Right. Merging two sorted logs takes one pass, $n$ comparisons, where sorting the combined list from scratch would take about $n\log n$. Taking A first on ties keeps the merge stable.
:::
:::
:::
