---
title: Problem set 1
heading: "Problem set 1: numbers and strings"
eyebrow: A4 · Problem set 1
type: problems
---

::: hook
These labs use lessons 1 to 5: values and functions, integers and floats, strings, and bits and bytes. Each one is a small piece of the bookkeeping engineers do every day, from reading a resistor's value to formatting a measurement. When a check fails, read the hidden test's message: it says which case went wrong.
:::

::: pool
pick: 5

::: check
kind: python

## Write `parse_value(s)` that reads a value written with an SI prefix (`p`, `n`, `u`, `m`, `k`, `M` or `G` as the last character, or none) and returns it as a float. Set `x = parse_value("680u")`.

```python starter
def parse_value(s):
    return float(s)

x = parse_value("680u")
print(x)
```

```python solution
def parse_value(s):
    prefixes = {"p": 1e-12, "n": 1e-9, "u": 1e-6, "m": 1e-3, "k": 1e3, "M": 1e6, "G": 1e9}
    if s[-1] in prefixes:
        return float(s[:-1]) * prefixes[s[-1]]
    return float(s)

x = parse_value("680u")
print(x)
```

```python tests
import math
assert math.isclose(parse_value("4.7k"), 4700), "4.7k should be 4700."
assert math.isclose(parse_value("1.5M"), 1.5e6) and math.isclose(parse_value("12m"), 0.012), "M is mega and m is milli: case matters."
assert math.isclose(parse_value("33n"), 33e-9) and math.isclose(parse_value("680u"), 680e-6), "n is 1e-9 and u is 1e-6."
assert math.isclose(parse_value("220"), 220), "A value with no prefix is read as it is."
assert math.isclose(x, 680e-6), "x should be parse_value('680u'), 0.00068."
```
:::

::: check
kind: python
given: v = 0.0047 | 4700 | 3.3e-7 | 1.5e6 | 0.22 | 82000

## Write `eng(x, unit)` returning a string like `"4.7 kΩ"`: the value scaled to a number from 1 up to (not including) 1000 with the matching prefix (`p`, `n`, `µ`, `m`, none, `k`, `M`, `G`), shown with `:g`, a space, then the prefix and unit. Set `s = eng(v, "Ω")` for `v` = {v}.

```python starter
def eng(x, unit):
    return f"{x} {unit}"

s = eng(v, "Ω")
print(s)
```

```python solution
import math

def eng(x, unit):
    prefixes = {-12: "p", -9: "n", -6: "µ", -3: "m", 0: "", 3: "k", 6: "M", 9: "G"}
    e = 3 * math.floor(math.log10(abs(x)) / 3)
    e = max(-12, min(9, e))
    return f"{round(x / 10**e, 6):g} {prefixes[e]}{unit}"

s = eng(v, "Ω")
print(s)
```

```python tests
assert eng(4700, "Ω") == "4.7 kΩ", f"4700 ohms should read '4.7 kΩ'; got {eng(4700, 'Ω')!r}."
assert eng(0.0047, "F") == "4.7 mF", f"0.0047 F should read '4.7 mF'; got {eng(0.0047, 'F')!r}."
assert eng(3.3e-7, "F") == "330 nF", f"3.3e-7 F should read '330 nF'; got {eng(3.3e-7, 'F')!r}."
assert eng(1.5e6, "Hz") == "1.5 MHz" and eng(0.22, "A") == "220 mA", "Check mega and milli."
assert eng(5, "V") == "5 V", "A value from 1 to 999 gets no prefix."
assert s == eng(v, "Ω"), "s should be eng(v, 'Ω') for this lab's value."
```
:::

::: check
kind: python
given: n = 1000 | 10000 | 100000

## Add `0.1` to a running total `n` = {n} times in a loop, starting from `0.0`. Set `total` to the result, `err` to `abs(total - n / 10)`, and `exact` to `math.fsum` of the same `n` values (which rounds only once).

```python starter
import math

total = 0.0
err = 0.0
exact = 0.0
print(total, err, exact)
```

```python solution
import math

total = 0.0
for _ in range(n):
    total += 0.1
err = abs(total - n / 10)
exact = math.fsum([0.1] * n)
print(total, err, exact)
```

```python tests
import math
t = 0.0
for _ in range(n):
    t += 0.1
assert total == t, "total should be the loop's result, added one 0.1 at a time."
assert err == abs(t - n / 10) and err > 0, "Adding 0.1 repeatedly drifts, because 0.1 has no exact binary form; err should be the drift."
assert exact == n / 10, "math.fsum rounds only once, so it lands exactly on n/10."
```
:::

::: check
kind: python
given: T = 59 | 3600 | 86399 | 45296 | 7322

## Write `hms(seconds)` returning a string `"h:mm:ss"` (hours with no padding, minutes and seconds with two digits) using `//` and `%`. Set `s = hms(T)` for `T` = {T}.

```python starter
def hms(seconds):
    return str(seconds)

s = hms(T)
print(s)
```

```python solution
def hms(seconds):
    h = seconds // 3600
    m = seconds % 3600 // 60
    sec = seconds % 60
    return f"{h}:{m:02d}:{sec:02d}"

s = hms(T)
print(s)
```

```python tests
assert hms(59) == "0:00:59", f"59 s is 0:00:59; got {hms(59)!r}."
assert hms(3600) == "1:00:00", f"3600 s is 1:00:00; got {hms(3600)!r}."
assert hms(45296) == "12:34:56", f"45296 s is 12:34:56; got {hms(45296)!r}."
assert hms(90061) == "25:01:01", "Hours aren't wrapped at 24."
assert s == hms(T), "s should be hms(T) for this lab's T."
```
:::

::: check
kind: python
given: x = 0.0012345 | 98765 | 3.14159 | 0.5 | 271.828; d = 2 | 3 | 4

## Write `sig(x, digits)` rounding a positive number to `digits` significant figures with `round` and `math.log10`. Set `y = sig(x, d)` for `x` = {x} and `d` = {d}.

```python starter
def sig(x, digits):
    return round(x, digits)

y = sig(x, d)
print(y)
```

```python solution
import math

def sig(x, digits):
    return round(x, digits - 1 - math.floor(math.log10(x)))

y = sig(x, d)
print(y)
```

```python tests
import math
assert sig(3.14159, 3) == 3.14 and sig(98765, 2) == 99000, "3 figures of pi is 3.14; 2 figures of 98765 is 99000."
assert math.isclose(sig(0.0012345, 2), 0.0012), "Leading zeros don't count as significant."
assert sig(0.5, 1) == 0.5 and math.isclose(sig(271.828, 4), 271.8), "Check numbers just below a power of ten and in the hundreds."
assert math.isclose(y, sig(x, d)), "y should be sig(x, d) for this lab's values."
```
:::

::: check
kind: python
given: reg = 0x5A3C | 0x1234 | 0xBEEF | 0x00F0

## A 16-bit status register packs fields: bits 0 to 3 are the channel, bits 4 to 7 the gain code, and bit 15 an error flag. Write `fields(reg)` returning `(channel, gain, error)` using `>>` and `&`, with `error` a `bool`. Set `f = fields(reg)` for `reg` = {reg:hex4}, and `h = f"{reg:04X}"`.

```python starter
def fields(reg):
    return 0, 0, False

f = fields(reg)
h = ""
print(f, h)
```

```python solution
def fields(reg):
    return reg & 0xF, (reg >> 4) & 0xF, bool(reg >> 15 & 1)

f = fields(reg)
h = f"{reg:04X}"
print(f, h)
```

```python tests
assert fields(0x5A3C) == (12, 3, False), f"0x5A3C has channel 12, gain 3 and no error; got {fields(0x5A3C)}."
assert fields(0xBEEF) == (15, 14, True), f"0xBEEF has channel 15, gain 14 and the error bit set; got {fields(0xBEEF)}."
assert fields(0x00F0) == (0, 15, False), "0x00F0 has channel 0 and gain 15."
assert f == fields(reg) and h == format(reg, "04X"), "f and h don't match this lab's register."
```
:::

::: check
kind: python

## A resistor's first two color bands are digits and the third is a power-of-ten multiplier (black 0, brown 1, red 2, orange 3, yellow 4, green 5, blue 6, violet 7, gray 8, white 9). Write `ohms(bands)` taking a string of three color names separated by spaces and returning the resistance in ohms. Set `r = ohms("orange white yellow")`.

```python starter
def ohms(bands):
    return 0

r = ohms("orange white yellow")
print(r)
```

```python solution
COLORS = ["black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "gray", "white"]

def ohms(bands):
    a, c, m = bands.split()
    return (10 * COLORS.index(a) + COLORS.index(c)) * 10 ** COLORS.index(m)

r = ohms("orange white yellow")
print(r)
```

```python tests
assert ohms("brown black red") == 1000, "brown black red is 10 x 100 = 1 kohm."
assert ohms("yellow violet orange") == 47000, "yellow violet orange is 47 x 1000 = 47 kohm."
assert ohms("green blue black") == 56, "A black multiplier means x 1."
assert r == 390000, "orange white yellow is 39 x 10,000 = 390 kohm."
```
:::
:::
