Skip to content

Ohm's Law algorithm added #3934

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Nov 25, 2020
Merged
39 changes: 39 additions & 0 deletions electronics/ohms_law.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# https://en.wikipedia.org/wiki/Ohm%27s_law


def ohms_law(voltage: float, current: float, resistance: float) -> float:
"""
Apply Ohm's Law, on any two given electrical values, which can be voltage, current,
and resistance, and then in a Python dict return name/value pair of the zero value.

>>> ohms_law(voltage=10, resistance=5, current=0)
{'current': 2.0}
>>> ohms_law(voltage=0, current=0, resistance=10)
Traceback (most recent call last):
...
ValueError: One and only one argument must be 0
>>> ohms_law(voltage=0, current=1, resistance=-2)
Traceback (most recent call last):
...
ValueError: Resistance cannot be negative
>>> ohms_law(resistance=0, voltage=-10, current=1)
{'resistance': -10.0}
>>> ohms_law(voltage=0, current=-1.5, resistance=2)
{'voltage': -3.0}
"""
if (voltage, current, resistance).count(0) != 1:
raise ValueError("One and only one argument must be 0")
if resistance < 0:
raise ValueError("Resistance cannot be negative")
if voltage == 0:
return {"voltage": float(current * resistance)}
elif current == 0:
return {"current": voltage / resistance}
elif resistance == 0:
return {"resistance": voltage / current}


if __name__ == "__main__":
import doctest

doctest.testmod()