forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproper_fractions.py
42 lines (37 loc) · 1.21 KB
/
proper_fractions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def gcd(numerator: int, denominator: int) -> int:
"""
>>> gcd(12, 18)
6
>>> gcd(20, 25)
5
>>> gcd(20, 0)
Traceback (most recent call last):
ValueError: The Denominator cannot be 0
"""
if denominator == 0:
raise ValueError("The Denominator cannot be 0")
while denominator:
numerator, denominator = denominator, numerator % denominator
return numerator
def proper_fractions(denominator: int) -> list[str]:
"""
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(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
>>>
"""
if denominator < 0:
raise ValueError("The Denominator Cannot be less than 0")
fractions: list[str] = []
for numerator in range(1, denominator):
if gcd(numerator, denominator) == 1:
fractions.append(f"{numerator}/{denominator}")
return fractions
if __name__ == "__main__":
__import__("doctest").testmod()