|
| 1 | +# https://en.wikipedia.org/wiki/Ohm%27s_law |
| 2 | + |
| 3 | + |
| 4 | +def ohms_law(voltage: float, current: float, resistance: float) -> float: |
| 5 | + """ |
| 6 | + Apply Ohm's Law, on any two given electrical values, which can be voltage, current, |
| 7 | + and resistance, and then in a Python dict return name/value pair of the zero value. |
| 8 | +
|
| 9 | + >>> ohms_law(voltage=10, resistance=5, current=0) |
| 10 | + {'current': 2.0} |
| 11 | + >>> ohms_law(voltage=0, current=0, resistance=10) |
| 12 | + Traceback (most recent call last): |
| 13 | + ... |
| 14 | + ValueError: One and only one argument must be 0 |
| 15 | + >>> ohms_law(voltage=0, current=1, resistance=-2) |
| 16 | + Traceback (most recent call last): |
| 17 | + ... |
| 18 | + ValueError: Resistance cannot be negative |
| 19 | + >>> ohms_law(resistance=0, voltage=-10, current=1) |
| 20 | + {'resistance': -10.0} |
| 21 | + >>> ohms_law(voltage=0, current=-1.5, resistance=2) |
| 22 | + {'voltage': -3.0} |
| 23 | + """ |
| 24 | + if (voltage, current, resistance).count(0) != 1: |
| 25 | + raise ValueError("One and only one argument must be 0") |
| 26 | + if resistance < 0: |
| 27 | + raise ValueError("Resistance cannot be negative") |
| 28 | + if voltage == 0: |
| 29 | + return {"voltage": float(current * resistance)} |
| 30 | + elif current == 0: |
| 31 | + return {"current": voltage / resistance} |
| 32 | + elif resistance == 0: |
| 33 | + return {"resistance": voltage / current} |
| 34 | + |
| 35 | + |
| 36 | +if __name__ == "__main__": |
| 37 | + import doctest |
| 38 | + |
| 39 | + doctest.testmod() |
0 commit comments