Skip to content

Commit bbd8714

Browse files
erdumamaank404cclauss
authored andcommitted
Ohm's Law algorithm added (TheAlgorithms#3934)
* New algorithm added * Errors resolvedc * New Algorithm * New algorithm added * Added new algorithm * work * New algorithm added * Hope this is final * Update electronics/ohms_law.py Co-authored-by: xcodz-dot <[email protected]> * update decimal value & negative value test * update as cclauss suggest * Update electronics/ohms_law.py Co-authored-by: Christian Clauss <[email protected]> * updated as suggested by cclauss * update as suggested by cclauss * Update as suggested by cclauss * Update ohms_law.py Co-authored-by: xcodz-dot <[email protected]> Co-authored-by: Christian Clauss <[email protected]>
1 parent 0dad591 commit bbd8714

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Diff for: electronics/ohms_law.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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

Comments
 (0)