MCPcopy
hub / github.com/TheAlgorithms/Python / ohms_law

Function ohms_law

electronics/ohms_law.py:5–36  ·  view source on GitHub ↗

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, resistan

(voltage: float, current: float, resistance: float)

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls 1

countMethod · 0.80

Tested by

no test coverage detected