---
title: Problem set 7
heading: "Problem set 7: arrays"
eyebrow: A4 · Problem set 7
type: problems
---

::: hook
These labs use lessons 28 to 30: NumPy arrays, vectorized arithmetic and two-dimensional arrays. Each one replaces a loop over measurements with a few array operations. Write them without Python loops where you can; the hidden tests check the results, and the message says which case went wrong.
:::

::: pool
pick: 5

::: check
kind: python
given: V = 3.3 | 5 | 12

## The starter has an array `R` of resistor values in ohms. Each sits alone across `V` = {V} V. Set `P` to the array of their powers, `total` to the total power, and `worst` to the index of the resistor that dissipates the most, without loops.

```python starter
import numpy as np
R = np.array([100, 220, 470, 1000, 47, 330, 150, 68])

P = np.zeros(len(R))
total = 0
worst = 0
print(P, total, worst)
```

```python solution
import numpy as np
R = np.array([100, 220, 470, 1000, 47, 330, 150, 68])

P = V**2 / R
total = P.sum()
worst = int(np.argmax(P))
print(P, total, worst)
```

```python tests
import numpy as np
assert np.allclose(P, V**2 / np.array([100, 220, 470, 1000, 47, 330, 150, 68])), "P should be V squared over each R."
assert np.isclose(total, np.sum(V**2 / R)), "total should add up every power."
assert worst == 4, f"The 47 ohm resistor, at index 4, dissipates the most; got {worst}."
```
:::

::: check
kind: python
given: th = 0.5 | 1 | 1.5

## The starter makes noisy samples `v`. Using a Boolean mask, set `frac` to the fraction of samples above `th` = {th} V, `mean_above` to the average of just those samples, and `n_neg` to how many are negative.

```python starter
import numpy as np
rng = np.random.default_rng(3)
v = 0.8 + 0.6 * rng.standard_normal(5000)

frac, mean_above, n_neg = 0, 0, 0
print(frac, mean_above, n_neg)
```

```python solution
import numpy as np
rng = np.random.default_rng(3)
v = 0.8 + 0.6 * rng.standard_normal(5000)

mask = v > th
frac = mask.mean()
mean_above = v[mask].mean()
n_neg = int((v < 0).sum())
print(frac, mean_above, n_neg)
```

```python tests
import numpy as np
assert np.isclose(frac, np.count_nonzero(v > th) / v.size), "frac should be the share of samples above the threshold."
assert np.isclose(mean_above, v[v > th].mean()), "mean_above should average only the samples above the threshold."
assert n_neg == np.count_nonzero(v < 0), "n_neg should count the negative samples."
assert mean_above > th, "Every sample in the mask is above the threshold, so their mean is too."
```
:::

::: check
kind: python
given: tau = 1 | 2 | 5

## A capacitor discharges into a 10 Ω resistor from 10 V with time constant `tau` = {tau} ms. The starter samples the power $p = v^2/R$ every 10 µs for 10 time constants. Set `E` to the energy delivered, by the trapezoid rule written with array slices (no `np.trapz`), and `exact` to $\tfrac12CV^2$ with $C = \tau/R$.

```python starter
import numpy as np
R, V0 = 10, 10
t = np.arange(0, 10 * tau * 1e-3, 1e-5)
p = (V0 * np.exp(-t / (tau * 1e-3)))**2 / R

E = 0
exact = 0
print(E, exact)
```

```python solution
import numpy as np
R, V0 = 10, 10
t = np.arange(0, 10 * tau * 1e-3, 1e-5)
p = (V0 * np.exp(-t / (tau * 1e-3)))**2 / R

E = np.sum((p[1:] + p[:-1]) / 2 * np.diff(t))
exact = 0.5 * (tau * 1e-3 / R) * V0**2
print(E, exact)
```

```python tests
import numpy as np
assert np.isclose(exact, 0.5 * tau * 1e-4 * 100), "exact should be (1/2) C V^2 with C = tau/R."
assert abs(E - exact) / exact < 1e-4, f"The trapezoid sum should land within 0.01% of the stored energy; got {E} against {exact}."
assert np.isclose(E, np.sum((p[1:] + p[:-1]) / 2 * np.diff(t))), "Use the trapezoid rule on the samples given."
```
:::

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

## A thermal camera's image of a board is the 2-D array `T` in °C (made in the starter). Set `hot` to the `(row, col)` of the hottest pixel using `np.argmax` and `np.unravel_index`, `row_means` to the mean of each row, and `over` to how many pixels in row `r` = {r} exceed 60 °C.

```python starter
import numpy as np
y, x = np.mgrid[0:6, 0:8]
T = 25 + 50 * np.exp(-((x - 5)**2 + (y - 2)**2) / 4) + 0.1 * x

hot = (0, 0)
row_means = np.zeros(6)
over = 0
print(hot, row_means, over)
```

```python solution
import numpy as np
y, x = np.mgrid[0:6, 0:8]
T = 25 + 50 * np.exp(-((x - 5)**2 + (y - 2)**2) / 4) + 0.1 * x

hot = tuple(int(i) for i in np.unravel_index(np.argmax(T), T.shape))
row_means = T.mean(axis=1)
over = int((T[r] > 60).sum())
print(hot, row_means, over)
```

```python tests
import numpy as np
assert hot == (2, 5), f"The hot spot is at row 2, column 5; got {hot}."
assert row_means.shape == (6,) and np.allclose(row_means, T.mean(axis=1)), "row_means should have one value per row."
assert over == int(np.count_nonzero(T[r] > 60)), f"over should count the pixels above 60 C in row {r}."
```
:::

::: check
kind: python
given: k = 0.25 | 0.4 | 0.6

## Using broadcasting, build `ratio`, a table of $R_2/(R_1 + R_2)$ with $R_1$ down the rows and $R_2$ across the columns, both from the starter's E12 list (1 kΩ to 8.2 kΩ). Set `n_good` to how many pairs land within 1% of the target `k` = {k}, and `best` to the `(R1, R2)` pair closest to it.

```python starter
import numpy as np
E12 = np.array([1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]) * 1e3

ratio = np.zeros((12, 12))
n_good = 0
best = (0, 0)
print(n_good, best)
```

```python solution
import numpy as np
E12 = np.array([1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]) * 1e3

R1 = E12[:, None]
R2 = E12[None, :]
ratio = R2 / (R1 + R2)
n_good = int((np.abs(ratio - k) <= 0.01 * k).sum())
i, j = np.unravel_index(np.argmin(np.abs(ratio - k)), ratio.shape)
best = (float(E12[i]), float(E12[j]))
print(n_good, best)
```

```python tests
import numpy as np
assert ratio.shape == (12, 12) and np.isclose(ratio[0, 0], 0.5) and np.isclose(ratio[0, 11], 8.2 / 9.2), "ratio[i, j] should be E12[j] / (E12[i] + E12[j])."
want = int(np.count_nonzero(np.abs(E12[None, :] / (E12[:, None] + E12[None, :]) - k) <= 0.01 * k))
assert n_good == want, f"There are {want} pairs within 1% of {k}; got {n_good}."
r = best[1] / (best[0] + best[1])
assert abs(r - k) == np.min(np.abs(ratio - k)), f"best should be the pair closest to {k}; {best} gives {r:.4f}."
```
:::

::: check
kind: python
given: A = 5 | 6 | 10; L = 2.5 | 4

## A sine of amplitude `A` = {A} V goes through a clipper that limits it to ±`L` = {L} V. Using `np.where` (or `np.clip`), set `out` to the clipped samples, `n_clipped` to how many samples were changed, and `rms_out` to the RMS of the output.

```python starter
import numpy as np
t = np.linspace(0, 1, 2000, endpoint=False)
v = A * np.sin(2 * np.pi * 5 * t)

out = v
n_clipped = 0
rms_out = 0
print(n_clipped, rms_out)
```

```python solution
import numpy as np
t = np.linspace(0, 1, 2000, endpoint=False)
v = A * np.sin(2 * np.pi * 5 * t)

out = np.where(v > L, L, np.where(v < -L, -L, v))
n_clipped = int((np.abs(v) > L).sum())
rms_out = np.sqrt(np.mean(out**2))
print(n_clipped, rms_out)
```

```python tests
import numpy as np
assert np.allclose(out, np.clip(v, -L, L)), "out should follow the input inside ±L and stick at the limit outside."
assert n_clipped == int(np.count_nonzero(np.abs(v) > L)), "n_clipped should count the samples beyond ±L."
assert np.isclose(rms_out, np.sqrt(np.mean(np.clip(v, -L, L)**2))), "rms_out should be the RMS of the clipped output."
assert rms_out < A / np.sqrt(2), "Clipping lowers the RMS below the sine's A/sqrt(2)."
```
:::

::: check
kind: python
given: th = 1.2 | 1.65 | 2.0

## A logic signal is sampled every microsecond. Threshold it at `th` = {th} V into 0s and 1s, then use `np.diff` to set `rises` to the sample indices where it goes from 0 to 1 (the index of the first 1), and `width` to the average number of samples each high pulse lasts.

```python starter
import numpy as np
n = np.arange(400)
v = 3.3 * ((n // 25) % 2) + 0.15 * np.sin(n)

rises = np.array([])
width = 0
print(rises, width)
```

```python solution
import numpy as np
n = np.arange(400)
v = 3.3 * ((n // 25) % 2) + 0.15 * np.sin(n)

bits = (v > th).astype(int)
d = np.diff(bits)
rises = np.nonzero(d == 1)[0] + 1
falls = np.nonzero(d == -1)[0] + 1
width = np.mean(falls - rises[:len(falls)])
print(rises, width)
```

```python tests
import numpy as np
assert list(rises) == [25, 75, 125, 175, 225, 275, 325, 375], f"The signal rises every 50 samples from 25; got {list(rises)}."
assert np.isclose(width, 25), f"Each high pulse lasts 25 samples; got {width}."
```
:::
:::
