---
title: Problem set 3
heading: "Problem set 3: lists, dictionaries and sets"
eyebrow: A4 · Problem set 3
type: problems
---

::: hook
These labs use lessons 12 and 13: lists, dictionaries and sets, with the loops and functions from before. Each one handles the kind of data a bench or a design produces: readings, parts lists and netlists. When a check fails, the hidden test's message says which case went wrong.
:::

::: pool
pick: 5

::: check
kind: python
given: th = 1 | 2 | 3

## Write `peaks(x, threshold)` returning the indices of the local maxima of a list: entries greater than both neighbors and above `threshold` (the first and last entries never count). Set `p = peaks(x, th)` for the starter's list and `th` = {th}.

```python starter
x = [0, 2.5, 1, 1.2, 3.4, 3.1, 0.5, 1.8, 1.6, 4.0, 2.2, 2.9, 0]

def peaks(x, threshold):
    return []

p = peaks(x, th)
print(p)
```

```python solution
x = [0, 2.5, 1, 1.2, 3.4, 3.1, 0.5, 1.8, 1.6, 4.0, 2.2, 2.9, 0]

def peaks(x, threshold):
    return [i for i in range(1, len(x) - 1) if x[i] > x[i - 1] and x[i] > x[i + 1] and x[i] > threshold]

p = peaks(x, th)
print(p)
```

```python tests
assert peaks(x, 1) == [1, 4, 7, 9, 11], f"Above 1, the peaks are at 1, 4, 7, 9 and 11; got {peaks(x, 1)}."
assert peaks(x, 3) == [4, 9], f"Above 3, only the peaks at 4 and 9 remain; got {peaks(x, 3)}."
assert peaks([5, 1, 5], 0) == [], "The ends never count as peaks."
assert peaks([1, 2, 2, 1], 0) == [], "A flat top isn't greater than both neighbors."
assert p == peaks(x, th), "p should be peaks(x, th) for this lab's threshold."
```
:::

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

## Two boards' parts lists are dictionaries from part number to quantity. Write `merge(a, b, boards_b=1)` returning one dictionary with the total of each part, where `b` is needed `boards_b` times. Set `m = merge(main, sensor, k)` for {k} sensor boards.

```python starter
main = {"R-10k": 12, "C-100n": 8, "U-LM358": 2}
sensor = {"R-10k": 3, "C-100n": 2, "U-TMP102": 1}

def merge(a, b, boards_b=1):
    return a

m = merge(main, sensor, k)
print(m)
```

```python solution
main = {"R-10k": 12, "C-100n": 8, "U-LM358": 2}
sensor = {"R-10k": 3, "C-100n": 2, "U-TMP102": 1}

def merge(a, b, boards_b=1):
    out = dict(a)
    for part, n in b.items():
        out[part] = out.get(part, 0) + n * boards_b
    return out

m = merge(main, sensor, k)
print(m)
```

```python tests
r = merge(main, sensor, 2)
assert r == {"R-10k": 18, "C-100n": 12, "U-LM358": 2, "U-TMP102": 2}, f"Two sensor boards add 6 resistors, 4 capacitors and 2 sensors; got {r}."
assert main == {"R-10k": 12, "C-100n": 8, "U-LM358": 2}, "merge shouldn't change the dictionaries it's given."
assert merge({}, {"X": 1}, 3) == {"X": 3}, "A part found only in b should appear with its count times boards_b."
assert m == merge(main, sensor, k), "m doesn't match this lab's board count."
```
:::

::: check
kind: python
given: n = 200 | 1000 | 5000

## Write `stats(x)` that makes a single pass over a list and returns `(lo, hi, rms)`, its minimum, maximum and RMS, without `min`, `max` or `sum`. Set `s = stats(v)` for the starter's `n` = {n} readings.

```python starter
import math
v = [math.sin(0.01 * i) * (1 + 0.001 * i) for i in range(n)]

def stats(x):
    return 0, 0, 0

s = stats(v)
print(s)
```

```python solution
import math
v = [math.sin(0.01 * i) * (1 + 0.001 * i) for i in range(n)]

def stats(x):
    lo = hi = x[0]
    sq = 0.0
    for a in x:
        if a < lo:
            lo = a
        if a > hi:
            hi = a
        sq += a * a
    return lo, hi, math.sqrt(sq / len(x))

s = stats(v)
print(s)
```

```python tests
import math
assert stats([3, -1, 4, 1, -5]) == (-5, 4, math.sqrt(52 / 5)), f"stats([3, -1, 4, 1, -5]) should be (-5, 4, 3.225); got {stats([3, -1, 4, 1, -5])}."
assert stats([2.0]) == (2.0, 2.0, 2.0), "One reading is its own min, max and RMS."
lo, hi, r = s
assert lo == min(v) and hi == max(v) and math.isclose(r, math.sqrt(sum(a * a for a in v) / len(v))), "s doesn't match the readings."
```
:::

::: check
kind: python
given: m = 3 | 5 | 8

## A test plan lists test points, and the bench log records which were measured (some more than once, and some by mistake that aren't in the plan). Using sets, set `missed` to the sorted list of planned points never measured, `extra` to the sorted list of measured points not in the plan, and `coverage` to the fraction of the plan measured, after logging `m` = {m} more points from the starter's `more` list.

```python starter
plan = ["TP1", "TP2", "TP3", "TP4", "TP5", "TP6", "TP7", "TP8", "TP9", "TP10"]
log = ["TP2", "TP5", "TP5", "TP11", "TP1"]
more = ["TP3", "TP9", "TP12", "TP3", "TP7", "TP10", "TP4", "TP6"]

missed, extra, coverage = [], [], 0
print(missed, extra, coverage)
```

```python solution
plan = ["TP1", "TP2", "TP3", "TP4", "TP5", "TP6", "TP7", "TP8", "TP9", "TP10"]
log = ["TP2", "TP5", "TP5", "TP11", "TP1"]
more = ["TP3", "TP9", "TP12", "TP3", "TP7", "TP10", "TP4", "TP6"]

done = set(log + more[:m])
missed = sorted(set(plan) - done)
extra = sorted(done - set(plan))
coverage = len(set(plan) & done) / len(plan)
print(missed, extra, coverage)
```

```python tests
done = set(log + more[:m])
assert missed == sorted(set(plan) - done), f"missed should be the planned points not yet measured; got {missed}."
assert extra == sorted(done - set(plan)), f"extra should be the measured points that aren't planned; got {extra}."
assert abs(coverage - len(set(plan) & done) / 10) < 1e-12, f"coverage should count each planned point once; got {coverage}."
assert "TP11" in extra, "TP11 was measured but isn't in the plan."
```
:::

::: check
kind: python
given: n = 500 | 800 | 1000 | 1500 | 2000 | 3000

## An ADC's noisy readings sit around one value. Using a dictionary, count how often each code appears, then set `mode` to the most common code (the smallest one if there's a tie), `spread` to the largest code minus the smallest, and `counts` to the dictionary. The starter makes `n` = {n} codes.

```python starter
import random
random.seed(7)
codes = [2048 + round(random.gauss(0, 1.5)) for _ in range(n)]

counts, mode, spread = {}, 0, 0
print(mode, spread)
```

```python solution
import random
random.seed(7)
codes = [2048 + round(random.gauss(0, 1.5)) for _ in range(n)]

counts = {}
for c in codes:
    counts[c] = counts.get(c, 0) + 1
best = max(counts.values())
mode = min(c for c, k in counts.items() if k == best)
spread = max(counts) - min(counts)
print(mode, spread)
```

```python tests
from collections import Counter
cnt = Counter(codes)
assert counts == dict(cnt), "counts should map every code to how many times it appears."
best = max(cnt.values())
assert mode == min(c for c, k in cnt.items() if k == best), f"mode should be the most common code; got {mode}."
assert spread == max(codes) - min(codes), f"spread should be the largest code minus the smallest; got {spread}."
```
:::

::: check
kind: python
given: r = 0 | 1 | 2

## A small sensor array's readings are a list of rows. Write `transpose(m)` returning its columns as rows, without NumPy, then set `t = transpose(grid)`, `col_sums` to the sum of each column, and `row_r` to row {r} of the transpose.

```python starter
grid = [[1.0, 2.5, 3.1, 0.4],
        [0.9, 2.2, 3.3, 0.6],
        [1.1, 2.4, 2.9, 0.5]]

def transpose(m):
    return m

t = transpose(grid)
col_sums = []
row_r = []
print(t, col_sums, row_r)
```

```python solution
grid = [[1.0, 2.5, 3.1, 0.4],
        [0.9, 2.2, 3.3, 0.6],
        [1.1, 2.4, 2.9, 0.5]]

def transpose(m):
    return [[row[j] for row in m] for j in range(len(m[0]))]

t = transpose(grid)
col_sums = [sum(c) for c in t]
row_r = t[r]
print(t, col_sums, row_r)
```

```python tests
import math
assert transpose([[1, 2, 3], [4, 5, 6]]) == [[1, 4], [2, 5], [3, 6]], "A 2 x 3 list becomes 3 x 2."
assert len(t) == 4 and len(t[0]) == 3, "The 3 x 4 grid should become 4 x 3."
assert all(math.isclose(a, b) for a, b in zip(col_sums, [3.0, 7.1, 9.3, 1.5])), f"The column sums are 3.0, 7.1, 9.3 and 1.5; got {col_sums}."
assert row_r == [row[r] for row in grid], "row_r should be column r of the original grid."
```
:::

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

## Each part is a tuple `(name, ohms, tolerance_percent)`. Set `ranked` to the list of names sorted by tolerance, tightest first, and by value within the same tolerance, then `top` to the first `k` = {k} names.

```python starter
parts = [("R1", 4700, 5), ("R2", 1000, 1), ("R3", 220, 5), ("R4", 10000, 0.1),
         ("R5", 330, 1), ("R6", 47000, 1), ("R7", 100, 0.1)]

ranked = []
top = []
print(ranked, top)
```

```python solution
parts = [("R1", 4700, 5), ("R2", 1000, 1), ("R3", 220, 5), ("R4", 10000, 0.1),
         ("R5", 330, 1), ("R6", 47000, 1), ("R7", 100, 0.1)]

ranked = [name for name, ohms, tol in sorted(parts, key=lambda p: (p[2], p[1]))]
top = ranked[:k]
print(ranked, top)
```

```python tests
assert ranked == ["R7", "R4", "R5", "R2", "R6", "R3", "R1"], f"Sort by tolerance, then by value; got {ranked}."
assert top == ranked[:k], "top should be the first k names."
```
:::
:::
