2020-11-29 22:07:10 +00:00
|
|
|
# https://en.m.wikipedia.org/wiki/Electric_power
|
2021-09-07 11:37:03 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2023-08-09 07:55:30 +00:00
|
|
|
from typing import NamedTuple
|
|
|
|
|
|
|
|
|
|
|
|
class Result(NamedTuple):
|
|
|
|
name: str
|
|
|
|
value: float
|
2020-11-29 22:07:10 +00:00
|
|
|
|
|
|
|
|
2021-09-07 11:37:03 +00:00
|
|
|
def electric_power(voltage: float, current: float, power: float) -> tuple:
|
2020-11-29 22:07:10 +00:00
|
|
|
"""
|
|
|
|
This function can calculate any one of the three (voltage, current, power),
|
|
|
|
fundamental value of electrical system.
|
|
|
|
examples are below:
|
|
|
|
>>> electric_power(voltage=0, current=2, power=5)
|
2023-08-09 07:55:30 +00:00
|
|
|
Result(name='voltage', value=2.5)
|
2020-11-29 22:07:10 +00:00
|
|
|
>>> electric_power(voltage=2, current=2, power=0)
|
2023-08-09 07:55:30 +00:00
|
|
|
Result(name='power', value=4.0)
|
2020-11-29 22:07:10 +00:00
|
|
|
>>> electric_power(voltage=-2, current=3, power=0)
|
2023-08-09 07:55:30 +00:00
|
|
|
Result(name='power', value=6.0)
|
2020-11-29 22:07:10 +00:00
|
|
|
>>> electric_power(voltage=2, current=4, power=2)
|
|
|
|
Traceback (most recent call last):
|
2022-10-23 14:36:10 +00:00
|
|
|
...
|
2020-11-29 22:07:10 +00:00
|
|
|
ValueError: Only one argument must be 0
|
|
|
|
>>> electric_power(voltage=0, current=0, power=2)
|
|
|
|
Traceback (most recent call last):
|
2022-10-23 14:36:10 +00:00
|
|
|
...
|
2020-11-29 22:07:10 +00:00
|
|
|
ValueError: Only one argument must be 0
|
|
|
|
>>> electric_power(voltage=0, current=2, power=-4)
|
|
|
|
Traceback (most recent call last):
|
2022-10-23 14:36:10 +00:00
|
|
|
...
|
2020-11-29 22:07:10 +00:00
|
|
|
ValueError: Power cannot be negative in any electrical/electronics system
|
|
|
|
>>> electric_power(voltage=2.2, current=2.2, power=0)
|
2023-08-09 07:55:30 +00:00
|
|
|
Result(name='power', value=4.84)
|
2020-11-29 22:07:10 +00:00
|
|
|
"""
|
|
|
|
if (voltage, current, power).count(0) != 1:
|
|
|
|
raise ValueError("Only one argument must be 0")
|
|
|
|
elif power < 0:
|
|
|
|
raise ValueError(
|
|
|
|
"Power cannot be negative in any electrical/electronics system"
|
|
|
|
)
|
|
|
|
elif voltage == 0:
|
2023-08-09 07:55:30 +00:00
|
|
|
return Result("voltage", power / current)
|
2020-11-29 22:07:10 +00:00
|
|
|
elif current == 0:
|
2023-08-09 07:55:30 +00:00
|
|
|
return Result("current", power / voltage)
|
2020-11-29 22:07:10 +00:00
|
|
|
elif power == 0:
|
2023-08-09 07:55:30 +00:00
|
|
|
return Result("power", float(round(abs(voltage * current), 2)))
|
2021-03-23 15:51:50 +00:00
|
|
|
else:
|
|
|
|
raise ValueError("Exactly one argument must be 0")
|
2020-11-29 22:07:10 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|