A422 of 56
0 XP
  1. Hook
  2. Problems

A4 · Problem set 5

Problem set 5: modules and classes

These labs use lessons 19 to 21: the standard library's modules, classes of your own, and state machines. Each one wraps an engineering idea (a resistor with a tolerance, a battery that drains, a filter) in a class, so the code that uses it reads like the circuit. When a check fails, the hidden test's message says which case went wrong.

Check

Write a class Resistor with attributes ohms, tol (percent) and rating (watts), and methods limits() returning (lowest, highest) values, power(v) returning the power at voltage v using the nominal value, and safe(v) returning True if the power is at most half the rating, at the lowest value (the worst case). Set r = Resistor(R, t, P) for 1000 Ω, 1%, 0.5 W, and ok = r.safe(V) at 12 V.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Write a class Battery(capacity_mAh) that starts full. draw(mA, hours) uses up that much charge (never below zero), percent() returns the charge left as a percentage of capacity, and hours_left(mA) how long it could still supply mA. Set b = Battery(C), call b.draw(I, h), and set left = b.percent() and more = b.hours_left(I) for 1000 mAh, 50 mA and 6 hours.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Write a class Phasor(mag, deg) that stores a complex value, with __add__ and __mul__ returning new Phasors, and properties mag and deg (the angle in degrees). Set s = Phasor(a, p) + Phasor(b, q) and m = Phasor(a, p) * Phasor(b, q) for 3∠30° and 4∠60°.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Using the fractions module, write parallel(*rs) returning the exact parallel combination of any number of resistances. Set R = parallel(Fraction(a), Fraction(b), Fraction(c)) for 6, 4 and 30 Ω, and top and bottom to its numerator and denominator in lowest terms.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Write a base class Filter whose gain(f) returns the magnitude of its complex H(f), with subclasses LowPass(fc) and HighPass(fc) that define H(f) for first-order RC filters. Then write cascade(filters, f) returning the product of their gains. Set g = cascade([HighPass(f1), LowPass(f2)], f) for a band-pass from 100 Hz to 5000 Hz, at 2000 Hz.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Have paper and a calculator ready. Work each problem out by hand, then enter the answer. Your first try on each one counts toward your score.

Practice

Keep practicing

8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.