Skip to content
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions electronics/electric_power.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# https://en.m.wikipedia.org/wiki/Electric_power

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
from collections import namedtuple
result = namedtuple("result", "name value")


def electric_power(voltage: float, current: float, power: float) -> float:
"""
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)
{'voltage': 2.5}
Copy link
Member

@cclauss cclauss Nov 28, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
{'voltage': 2.5}
result(name='voltage', value=2.5)

>>> electric_power(voltage=2, current=2, power=0)
{'power': 4.0}
>>> electric_power(voltage=-2, current=3, power=0)
{'power': 6.0}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to test:

  1. No zeros
  2. Two zeros
  3. Negative numbers for power
  4. Floating-point numbers
Suggested change
{'power': 6.0}
>>> electric_power(voltage=-2, current=3, power=0).name
'power'
>>> electric_power(voltage=-2, current=3, power=0).value
6.0

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, should i also do this on ohms_law as well??

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's get this PR landed before you modify Ohm's law...

Coincidentally, @rhettinger (who wrote the namedtuple) just tweeted about Ohm's law...
https://twitter.com/raymondh/status/1331850115674345473

"""
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:
return {"voltage": power / current}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return {"voltage": power / current}
return result("voltage", power / current)

elif current == 0:
return {"current": power / voltage}
elif power == 0:
return {"power": float(abs(voltage * current))}


if __name__ == "__main__":
import doctest

doctest.testmod()