|
| 1 | +"""Electrical impedance is the measure of the opposition that a |
| 2 | +circuit presents to a current when a voltage is applied. |
| 3 | +Impedance extends the concept of resistance to alternating current (AC) circuits. |
| 4 | +Source: https://en.wikipedia.org/wiki/Electrical_impedance |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +from math import pow, sqrt |
| 10 | + |
| 11 | + |
| 12 | +def electrical_impedance( |
| 13 | + resistance: float, reactance: float, impedance: float |
| 14 | +) -> dict[str, float]: |
| 15 | + """ |
| 16 | + Apply Electrical Impedance formula, on any two given electrical values, |
| 17 | + which can be resistance, reactance, and impedance, and then in a Python dict |
| 18 | + return name/value pair of the zero value. |
| 19 | +
|
| 20 | + >>> electrical_impedance(3,4,0) |
| 21 | + {'impedance': 5.0} |
| 22 | + >>> electrical_impedance(0,4,5) |
| 23 | + {'resistance': 3.0} |
| 24 | + >>> electrical_impedance(3,0,5) |
| 25 | + {'reactance': 4.0} |
| 26 | + >>> electrical_impedance(3,4,5) |
| 27 | + Traceback (most recent call last): |
| 28 | + ... |
| 29 | + ValueError: One and only one argument must be 0 |
| 30 | + """ |
| 31 | + if (resistance, reactance, impedance).count(0) != 1: |
| 32 | + raise ValueError("One and only one argument must be 0") |
| 33 | + if resistance == 0: |
| 34 | + return {"resistance": sqrt(pow(impedance, 2) - pow(reactance, 2))} |
| 35 | + elif reactance == 0: |
| 36 | + return {"reactance": sqrt(pow(impedance, 2) - pow(resistance, 2))} |
| 37 | + elif impedance == 0: |
| 38 | + return {"impedance": sqrt(pow(resistance, 2) + pow(reactance, 2))} |
| 39 | + else: |
| 40 | + raise ValueError("Exactly one argument must be 0") |
| 41 | + |
| 42 | + |
| 43 | +if __name__ == "__main__": |
| 44 | + import doctest |
| 45 | + |
| 46 | + doctest.testmod() |
0 commit comments