---
title: "Lab: parts lists, netlists and tests"
heading: Organizing a design's data, and proving the code that handles it
eyebrow: A4 · Lesson 17 · Lab: parts lists, netlists and tests
xp: 60
---

::: hook
Behind every board is a pile of structured data: a bill of materials with quantities and price breaks, a netlist of which pins connect where, a log of measurements against their nominal values. Lessons 12 to 16 gave you lists, dictionaries and sets, the iteration patterns that walk them, and exceptions and tests to keep the code honest. This lab costs a production run, checks a netlist for loose ends, reads a messy log without crashing, rounds to standard values across every decade, and ranks parts by how far they're off.
:::

::: predict
## A netlist lists each part with the two nodes it connects. A node that appears exactly once usually means what?

- [x] A wire that goes nowhere: a part with one end unconnected
- [ ] Ground
- [ ] The most important node in the circuit
- [ ] Nothing in particular

::: reveal
A loose end. Every real node joins at least two things, or no current can flow through it, so a node named only once is almost always a typo or a forgotten connection. Counting each node's connections in a dictionary finds them all in one pass, and schematic tools run exactly this check before they let you make a board.
:::
:::

::: nameit
## Patterns this lab uses

- **Dictionaries of records:** `bom = {"R1": (qty, price, price100)}` keeps each part's fields together under its name; `for name, (q, p1, p100) in bom.items():` unpacks them.
- **Counting:** `count[n] = count.get(n, 0) + 1` tallies anything, and a comprehension filters the tally.
- **Sorting by a computed key:** `sorted(rows, key=lambda r: r[1], reverse=True)` ranks by any field.
- **Errors as data:** wrap the risky line in `try`/`except ValueError`, record what failed, and keep going.
- **Edge cases first:** before trusting a function, try the inputs at its boundaries, such as a value exactly between two choices or at a decade edge.
:::

::: example
## A board uses 4 of R1 (0.010 dollars each, 0.004 from 100 up), 2 of C1 (0.050, or 0.020 from 100), 1 of U1 (1.20, or 0.95 from 100) and 1 of J1 (0.40, or 0.31 from 100). What do the parts cost for 10, 50 and 100 boards?

::: solution
1. **Cost each part at its total quantity.** The price break applies to the total quantity of each part, so the quantity per board multiplies first.

```python
bom = {"R1": (4, 0.010, 0.004), "C1": (2, 0.050, 0.020),
       "U1": (1, 1.20, 0.95), "J1": (1, 0.40, 0.31)}

def cost(boards):
    total = 0
    for name, (q, p1, p100) in bom.items():
        n = q * boards
        total += n * (p100 if n >= 100 else p1)
    return total

print(cost(10), cost(50), cost(100))    # 17.4 82.8 131.6
```

2. **Ten boards.** They cost 17.40 dollars, 1.74 a board.
3. **Fifty boards.** The resistors (200 pieces) and capacitors (100) reach their price break but U1 and J1 don't, so it's 82.80 dollars, or 1.66 a board.
4. **A hundred boards.** Everything reaches its break: 131.60 dollars, 1.32 a board.

**Answer:** the parts cost 17.40 dollars for 10 boards, 82.80 for 50 and 131.60 for 100 (1.74, 1.66 and 1.32 dollars a board).
:::
:::

::: example
## Find the loose ends in the netlist R1 in–a, R2 a–out, C1 out–gnd, R3 b–gnd, V1 in–gnd.

::: solution
1. **Count how often each node appears.** A node that appears only once is a loose end.

```python
net = [("R1", "in", "a"), ("R2", "a", "out"), ("C1", "out", "gnd"),
       ("R3", "b", "gnd"), ("V1", "in", "gnd")]
count = {}
for part, a, b in net:
    for node in (a, b):
        count[node] = count.get(node, 0) + 1
print(sorted(n for n, c in count.items() if c == 1))    # ['b']
```

2. **Find the loose end.** Node `b` appears only once, on R3: that resistor hangs off ground with nothing at its other end.
3. **Say where to look.** Probably R3 was meant to go to `a` or `out`. The tool can't say which, but it can say where to look.

**Answer:** node `b` is the only loose end, so R3 is connected at ground alone.
:::
:::

::: check
kind: python
given: boards = 10 | 25 | 50 | 100 | 250

## Using the starter's bill of materials, write `cost(boards)` returning the parts cost in dollars for a run, where each part's lower price applies once its total quantity reaches 100. Then set `total = cost(boards)` for `boards` = {boards} and `each` to the cost per board.

```python starter
bom = {"R1": (4, 0.010, 0.004), "C1": (2, 0.050, 0.020), "U1": (1, 1.20, 0.95),
       "J1": (1, 0.40, 0.31), "L1": (1, 0.25, 0.18), "D1": (2, 0.03, 0.012)}

def cost(boards):
    return sum(q * p1 for q, p1, p100 in bom.values()) * boards

total = cost(boards)
each = 0
print(total, each)
```

```python solution
bom = {"R1": (4, 0.010, 0.004), "C1": (2, 0.050, 0.020), "U1": (1, 1.20, 0.95),
       "J1": (1, 0.40, 0.31), "L1": (1, 0.25, 0.18), "D1": (2, 0.03, 0.012)}

def cost(boards):
    total = 0
    for name, (q, p1, p100) in bom.items():
        n = q * boards
        total += n * (p100 if n >= 100 else p1)
    return total

total = cost(boards)
each = total / boards
print(total, each)
```

```python tests
B = {"R1": (4, 0.010, 0.004), "C1": (2, 0.050, 0.020), "U1": (1, 1.20, 0.95), "J1": (1, 0.40, 0.31), "L1": (1, 0.25, 0.18), "D1": (2, 0.03, 0.012)}
want = sum(q * boards * (c if q * boards >= 100 else p) for q, p, c in B.values())
assert abs(total - want) < 1e-9, f"For {boards} boards the parts cost {want:.2f} dollars. The break depends on each part's total quantity, q * boards."
assert abs(each - want / boards) < 1e-12, "each is total / boards."
```

::: right
Right. Each part crosses its price break at a different run size, so the cost per board falls in steps as the run grows.
:::
:::

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

## Write `loose_ends(net)` returning the sorted list of nodes that appear only once in a netlist of `(part, node_a, node_b)` tuples, and `shorted(net)` returning the sorted list of parts whose two ends are on the same node. Set `ends` and `shorts` for the netlist the starter picks.

```python starter
nets = [[("R1", "in", "a"), ("R2", "a", "out"), ("C1", "out", "gnd"), ("R3", "b", "gnd"), ("V1", "in", "gnd")],
        [("V1", "vcc", "gnd"), ("R1", "vcc", "x"), ("R2", "x", "x"), ("C1", "x", "gnd"), ("D1", "y", "z")],
        [("V1", "in", "gnd"), ("R1", "in", "out"), ("R2", "out", "gnd"), ("C1", "gnd", "gnd")]]
net = nets[k]

def loose_ends(net):
    return []

def shorted(net):
    return []

ends = loose_ends(net)
shorts = shorted(net)
print(ends, shorts)
```

```python solution
nets = [[("R1", "in", "a"), ("R2", "a", "out"), ("C1", "out", "gnd"), ("R3", "b", "gnd"), ("V1", "in", "gnd")],
        [("V1", "vcc", "gnd"), ("R1", "vcc", "x"), ("R2", "x", "x"), ("C1", "x", "gnd"), ("D1", "y", "z")],
        [("V1", "in", "gnd"), ("R1", "in", "out"), ("R2", "out", "gnd"), ("C1", "gnd", "gnd")]]
net = nets[k]

def loose_ends(net):
    count = {}
    for part, a, b in net:
        for node in (a, b):
            count[node] = count.get(node, 0) + 1
    return sorted(n for n, c in count.items() if c == 1)

def shorted(net):
    return sorted(part for part, a, b in net if a == b)

ends = loose_ends(net)
shorts = shorted(net)
print(ends, shorts)
```

```python tests
assert ends == [["b"], ["y", "z"], []][k], f"The loose ends here are {[['b'], ['y', 'z'], []][k]}."
assert shorts == [[], ["R2"], ["C1"]][k], f"The shorted parts here are {[[], ['R2'], ['C1']][k]}."
```

::: right
Right. A part with both ends on one node counts that node twice, which is why the shorted check is separate: R2 from `x` to `x` hides nothing from the loose-end count but does nothing in the circuit. D1 floating between `y` and `z` shows up as two loose ends.
:::
:::

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

## The starter's log has lines like `R7=4712.3`, but some are damaged. Write `read_log(lines)` returning `(values, bad)`: a dictionary from name to float for the good lines, and a list of the line numbers (counting from 1) that couldn't be read, whether the `=` is missing or the value isn't a number. Set `values, bad = read_log(lines)`.

```python starter
logs = [["R1=4700.2", "R2=10012", "R3=?", "C1=1.02e-7"],
        ["V1=3.301", "V2", "V3=5.0V", "V4=12.004", ""],
        ["a=1", "b=2", "c=3", "d==4"]]
lines = logs[k]

def read_log(lines):
    values = {}
    for line in lines:
        name, v = line.split("=")
        values[name] = float(v)
    return values, []

values, bad = read_log(lines)
print(values, bad)
```

```python solution
logs = [["R1=4700.2", "R2=10012", "R3=?", "C1=1.02e-7"],
        ["V1=3.301", "V2", "V3=5.0V", "V4=12.004", ""],
        ["a=1", "b=2", "c=3", "d==4"]]
lines = logs[k]

def read_log(lines):
    values, bad = {}, []
    for i, line in enumerate(lines, start=1):
        try:
            name, v = line.split("=")
            values[name.strip()] = float(v)
        except ValueError:
            bad.append(i)
    return values, bad

values, bad = read_log(lines)
print(values, bad)
```

```python tests
want_v = [{"R1": 4700.2, "R2": 10012.0, "C1": 1.02e-7}, {"V1": 3.301, "V4": 12.004}, {"a": 1.0, "b": 2.0, "c": 3.0}][k]
want_b = [[3], [2, 3, 5], [4]][k]
assert values == want_v, f"The good lines give {want_v}."
assert bad == want_b, f"The damaged lines are {want_b}, counting from 1."
```

::: right
Right. A missing `=` makes the unpacking fail and a bad number makes `float` fail, and both raise `ValueError`, so one `except` catches them. Recording the line numbers turns a crash into a report someone can act on.
:::
:::

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

## Write `nearest_e12(x)` returning the E12 value nearest to any positive `x` in ratio (smallest $|\log(v/x)|$), searching the decade below, the decade of `x` and the decade above. Set `r = [nearest_e12(x) for x in xs]` for the starter's list.

```python starter
import math
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
xs = [[9.6, 4700, 0.0335, 1.1], [91.2, 0.0012, 3.1e6, 5.0], [0.95, 150, 7.4, 2.45e-9], [8.7, 9.2, 10.5, 1.09]][k]

def nearest_e12(x):
    d = 10 ** math.floor(math.log10(x))
    return min((m * d for m in E12), key=lambda v: abs(v - x))

r = [nearest_e12(x) for x in xs]
print(r)
```

```python solution
import math
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
xs = [[9.6, 4700, 0.0335, 1.1], [91.2, 0.0012, 3.1e6, 5.0], [0.95, 150, 7.4, 2.45e-9], [8.7, 9.2, 10.5, 1.09]][k]

def nearest_e12(x):
    p = math.floor(math.log10(x))
    candidates = [m * 10.0**e for e in (p - 1, p, p + 1) for m in E12]
    return min(candidates, key=lambda v: abs(math.log(v / x)))

r = [nearest_e12(x) for x in xs]
print(r)
```

```python tests
import math
E = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
def ref(x):
    p = math.floor(math.log10(x))
    return min((m * 10.0**e for e in range(p - 2, p + 3) for m in E), key=lambda v: abs(math.log(v / x)))
for x, got in zip(xs, r):
    assert abs(got / ref(x) - 1) < 1e-9, f"The nearest E12 value to {x} is {ref(x):g}. Values just under a decade, like 9.6, round up to the next decade's 1.0."
```

::: right
Right. 9.6 is nearer 10 than 8.2, so the search has to look into the next decade, and "nearest" means nearest in ratio, because the E series is spaced in equal ratios. The starter finds neither.
:::
:::

::: check
kind: python
given: k = 1..4 int; tol = 1 | 2 | 5

## The starter has `nominal` and `measured` dictionaries for the same parts. Set `report` to a list of `(name, error_pct)` for the parts whose error, $100(\text{measured} - \text{nominal})/\text{nominal}$, is bigger in size than `tol` = {tol}%, sorted from the largest size of error to the smallest.

```python starter
import random
random.seed(k)
nominal = {f"R{i}": random.choice([1e3, 2.2e3, 4.7e3, 10e3]) for i in range(1, 13)}
measured = {n: v * (1 + random.uniform(-0.07, 0.07)) for n, v in nominal.items()}
report = [(n, 100 * (measured[n] - v) / v) for n, v in nominal.items()]
print(report)
```

```python solution
import random
random.seed(k)
nominal = {f"R{i}": random.choice([1e3, 2.2e3, 4.7e3, 10e3]) for i in range(1, 13)}
measured = {n: v * (1 + random.uniform(-0.07, 0.07)) for n, v in nominal.items()}
errs = [(n, 100 * (measured[n] - v) / v) for n, v in nominal.items()]
report = sorted([(n, e) for n, e in errs if abs(e) > tol], key=lambda r: abs(r[1]), reverse=True)
print(report)
```

```python tests
import random
random.seed(k)
nom = {f"R{i}": random.choice([1e3, 2.2e3, 4.7e3, 10e3]) for i in range(1, 13)}
mea = {n: v * (1 + random.uniform(-0.07, 0.07)) for n, v in nom.items()}
want = sorted([(n, 100 * (mea[n] - v) / v) for n, v in nom.items() if abs(100 * (mea[n] - v) / v) > tol], key=lambda r: abs(r[1]), reverse=True)
assert [n for n, e in report] == [n for n, e in want], f"The parts out of ±{tol}%, worst first, are {[n for n, e in want]}."
assert all(abs(a[1] - b[1]) < 1e-9 for a, b in zip(report, want)), "Keep each error's sign: a part can be high or low."
```

::: right
Right. Sorting by `abs(error)` ranks the worst parts first whichever way they're off, while the report keeps the sign so you can see whether a batch runs high or low.
:::
:::

::: check
kind: choice

## `d = {"R1": 4700}`. What is `d.get("R2", 0)`?

- [x] `0`
- [ ] `None`
- [ ] `4700`
- [ ] A `KeyError`

::: right
Right. `get` returns the default you give it when the key is missing, instead of raising an error as `d["R2"]` would.
:::

::: misses
- [2] `None` is what `get` returns when you don't give a default. Here the default is 0.
- [3] That's the value for `"R1"`. `"R2"` isn't in the dictionary.
- [4] `d["R2"]` would raise `KeyError`; `get` is the method that doesn't.
:::
:::

::: explain
## The rounding function's tests include 9.6 and 0.95. Why are values like these worth testing in particular?

::: model
They sit just below a decade boundary, where the nearest standard value is in the next decade up: 9.6 rounds to 10 and 0.95 to 1.0. A function that only searches the decade the value is in gets every ordinary value right and these wrong, so tests made only of typical values would pass a broken function. Good tests aim at the places where the logic changes, the boundaries, because that's where bugs live.
:::
:::
