Skip to content

adding a proper fractions algorithm #11224

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 10 commits into from
Mar 20, 2024
37 changes: 37 additions & 0 deletions maths/numerical_analysis/proper_fractions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from math import gcd
import doctest


def proper_fractions(denominator: int) -> list[str]:

Check failure on line 5 in maths/numerical_analysis/proper_fractions.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

maths/numerical_analysis/proper_fractions.py:1:1: I001 Import block is un-sorted or un-formatted
"""
this algorithm returns a list of proper fractions, in the
range between 0 and 1, which can be formed with the given denominator
proper fractions: https://en.wikipedia.org/wiki/Fraction#:~:text=Proper%20and%20improper,and%203/3.

>>> proper_fractions(10)
['1/10', '3/10', '7/10', '9/10']
>>> proper_fractions(5)
['1/5', '2/5', '3/5', '4/5']
>>> proper_fractions(-15)
Traceback (most recent call last):
ValueError: The Denominator Cannot be less than 0
>>> proper_fractions(0)
[]
>>> proper_fractions(1.2)
Traceback (most recent call last):
ValueError: The Denominator has to be an integer
"""

if denominator < 0:
raise ValueError("The Denominator Cannot be less than 0")
elif isinstance(denominator, float):
raise ValueError("The Denominator has to be an integer")
return [
f"{numerator}/{denominator}"
for numerator in range(1, denominator)
if gcd(numerator, denominator) == 1
]


if __name__ == "__main__":
doctest.testmod()
Loading