---
title: Midterm exam
heading: "Midterm exam: Python fundamentals"
eyebrow: A4 · Midterm exam
type: problems
---

::: hook
Five labs covering lessons 1 to 25. Give yourself two hours and work without the lessons open. Each lab is graded by hidden tests; read their messages if a check fails, fix, and check again. "Another set" deals a different exam.
:::

::: pool
pick: 5

::: check
kind: python
given: Vs = 9 | 12 | 24; R1 = 1k..47k E12; R2 = 1k..47k E12

## Write `divider(Vs, R1, R2)` returning a tuple `(Vout, I, P)`: the output voltage, the current through the chain and the total power. Set `Vout, I, P = divider(Vs, R1, R2)`.

```python starter
def divider(Vs, R1, R2):
    return 0

Vout, I, P = 0, 0, 0
print(Vout, I, P)
```

```python solution
def divider(Vs, R1, R2):
    I = Vs / (R1 + R2)
    return I * R2, I, Vs * I

Vout, I, P = divider(Vs, R1, R2)
print(Vout, I, P)
```

```python tests
import math
v, i, p = divider(12, 10e3, 20e3)
assert math.isclose(v, 8) and math.isclose(i, 4e-4) and math.isclose(p, 4.8e-3), "divider(12, 10e3, 20e3) should be (8.0, 0.0004, 0.0048)."
assert math.isclose(Vout, Vs * R2 / (R1 + R2)), "Vout doesn't match."
```
:::

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

## Write `eng(x)` formatting a positive number with an SI prefix and three significant figures (p, n, u, m, none, k, M), like `eng(0.0047)` → `"4.7m"`. Set `out` to the list of `eng` applied to the starter's values.

```python starter
import math
vals = [[4700, 0.0047, 1e-9], [2.2e6, 330, 0.1], [15e-12, 68e-6, 1], [999, 1000, 0.001]][k]

def eng(x):
    return str(x)

out = [eng(v) for v in vals]
print(out)
```

```python solution
import math
vals = [[4700, 0.0047, 1e-9], [2.2e6, 330, 0.1], [15e-12, 68e-6, 1], [999, 1000, 0.001]][k]

def eng(x):
    p = math.floor(math.log10(x) / 3)
    p = max(-4, min(2, p))
    prefix = {-4: "p", -3: "n", -2: "u", -1: "m", 0: "", 1: "k", 2: "M"}[p]
    return f"{x / 1000**p:.3g}{prefix}"

out = [eng(v) for v in vals]
print(out)
```

```python tests
want = [["4.7k", "4.7m", "1n"], ["2.2M", "330", "100m"], ["15p", "68u", "1"], ["999", "1k", "1m"]][k]
assert out == want, f"out should be {want}."
```
:::

::: check
kind: python
given: a = 2 | 3 | 10

## Use Newton's update $x \leftarrow x - (x^3 - a)/(3x^2)$ from $x = a$ until $|x^3 - a| < 10^{-12}a$, and set `x` to the cube root of `a` = {a} and `steps` to the number of updates.

```python starter
x = a
steps = 0
print(x, steps)
```

```python solution
x = float(a)
steps = 0
while abs(x**3 - a) >= 1e-12 * a:
    x = x - (x**3 - a) / (3 * x**2)
    steps += 1
print(x, steps)
```

```python tests
assert abs(x**3 - a) < 1e-12 * a, "x isn't converged yet."
assert 0 < steps < 50, "Count the updates."
```
:::

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

## Set `by_node` to a dictionary from each node to the sorted list of part names connected to it.

```python starter
netlist = [[("R1", "in", "a"), ("C1", "a", "0"), ("R2", "a", "out"), ("C2", "out", "0")],
           [("V1", "p", "0"), ("D1", "p", "q"), ("R1", "q", "0")],
           [("L1", "x", "y"), ("R1", "y", "0"), ("C1", "x", "y")]][k]
by_node = {}
print(by_node)
```

```python solution
netlist = [[("R1", "in", "a"), ("C1", "a", "0"), ("R2", "a", "out"), ("C2", "out", "0")],
           [("V1", "p", "0"), ("D1", "p", "q"), ("R1", "q", "0")],
           [("L1", "x", "y"), ("R1", "y", "0"), ("C1", "x", "y")]][k]
by_node = {}
for name, a, b in netlist:
    for node in (a, b):
        by_node.setdefault(node, []).append(name)
for node in by_node:
    by_node[node].sort()
print(by_node)
```

```python tests
want = [{"in": ["R1"], "a": ["C1", "R1", "R2"], "0": ["C1", "C2"], "out": ["C2", "R2"]},
        {"p": ["D1", "V1"], "0": ["R1", "V1"], "q": ["D1", "R1"]},
        {"x": ["C1", "L1"], "y": ["C1", "L1", "R1"], "0": ["R1"]}][k]
assert by_node == want, f"by_node should be {want}."
```
:::

::: check
kind: python
given: t = 1 | 5 | 10

## Write a class `Res` with `value` and `tol` (a fraction), a method `bounds()`, and a function `series_bounds(parts)` returning the lowest and highest total of a list of `Res` in series. Set `lo, hi = series_bounds([Res(1000, t / 100), Res(2200, t / 100), Res(470, t / 100)])`.

```python starter
class Res:
    pass

lo, hi = 0, 0
print(lo, hi)
```

```python solution
class Res:
    def __init__(self, value, tol):
        self.value = value
        self.tol = tol

    def bounds(self):
        return self.value * (1 - self.tol), self.value * (1 + self.tol)

def series_bounds(parts):
    return sum(p.bounds()[0] for p in parts), sum(p.bounds()[1] for p in parts)

lo, hi = series_bounds([Res(1000, t / 100), Res(2200, t / 100), Res(470, t / 100)])
print(lo, hi)
```

```python tests
import math
assert math.isclose(lo, 3670 * (1 - t / 100)) and math.isclose(hi, 3670 * (1 + t / 100)), "The series total runs from the sum of the lows to the sum of the highs."
```
:::

::: check
kind: python
given: f = 0.3 | 0.55 | 0.8

## A rising signal is sampled once a millisecond: sample $k$ is $1 - e^{-k/7}$. Using binary search over $k$ from 0 to 1000, set `k` to the first sample at or above `f` = {f}.

```python starter
import math
k = 0
print(k)
```

```python solution
import math
lo, hi = 0, 1000
while lo < hi:
    mid = (lo + hi) // 2
    if 1 - math.exp(-mid / 7) < f:
        lo = mid + 1
    else:
        hi = mid
k = lo
print(k)
```

```python tests
import math
assert 1 - math.exp(-k / 7) >= f and (k == 0 or 1 - math.exp(-(k - 1) / 7) < f), "k should be the first sample at or above f."
```
:::

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

## The starter's `slow_dupes` is quadratic. Write `fast_dupes(x)` that returns the same sorted list of repeated values in one pass with sets, and set `d = fast_dupes(x)`.

```python starter
def slow_dupes(x):
    out = []
    for i in range(len(x)):
        for j in range(i + 1, len(x)):
            if x[i] == x[j] and x[i] not in out:
                out.append(x[i])
    return sorted(out)

def fast_dupes(x):
    return []

x = [[4, 8, 15, 16, 23, 42, 8, 15], [1, 1, 2, 3, 5, 8, 13, 21, 1], [9, 7, 9, 7, 9]][k]
d = fast_dupes(x)
print(d)
```

```python solution
def fast_dupes(x):
    seen, dup = set(), set()
    for v in x:
        if v in seen:
            dup.add(v)
        seen.add(v)
    return sorted(dup)

x = [[4, 8, 15, 16, 23, 42, 8, 15], [1, 1, 2, 3, 5, 8, 13, 21, 1], [9, 7, 9, 7, 9]][k]
d = fast_dupes(x)
print(d)
```

```python tests
assert d == [[8, 15], [1], [7, 9]][k], "d should list each repeated value once, sorted."
assert fast_dupes([5, 1, 5, 1, 2]) == [1, 5], "fast_dupes([5, 1, 5, 1, 2]) should be [1, 5]."
```
:::

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

## Write `parse_all(texts)` returning the list of values in base units for strings like `"4.7k"`, skipping (not crashing on) any string that can't be read. Set `vals = parse_all(texts)`.

```python starter
MULT = {"p": 1e-12, "n": 1e-9, "u": 1e-6, "m": 1e-3, "k": 1e3, "M": 1e6}

def parse_all(texts):
    return [float(t) for t in texts]

texts = [["4.7k", "bad", "100n", "12"], ["1M", "2.2u", "?", "x1"], ["330", "47p", "1.5m"]][k]
vals = []
print(vals)
```

```python solution
MULT = {"p": 1e-12, "n": 1e-9, "u": 1e-6, "m": 1e-3, "k": 1e3, "M": 1e6}

def parse_all(texts):
    out = []
    for t in texts:
        try:
            if t and t[-1] in MULT:
                out.append(float(t[:-1]) * MULT[t[-1]])
            else:
                out.append(float(t))
        except ValueError:
            pass
    return out

texts = [["4.7k", "bad", "100n", "12"], ["1M", "2.2u", "?", "x1"], ["330", "47p", "1.5m"]][k]
vals = parse_all(texts)
print(vals)
```

```python tests
import math
want = [[4700, 1e-7, 12], [1e6, 2.2e-6], [330, 4.7e-11, 1.5e-3]][k]
assert len(vals) == len(want) and all(math.isclose(a, b) for a, b in zip(vals, want)), f"vals should be {want}."
```
:::
:::
