|
| 1 | +from math import gcd |
| 2 | + |
| 3 | + |
| 4 | +def proper_fractions(denominator: int) -> list[str]: |
| 5 | + """ |
| 6 | + this algorithm returns a list of proper fractions, in the |
| 7 | + range between 0 and 1, which can be formed with the given denominator |
| 8 | + https://en.wikipedia.org/wiki/Fraction#Proper_and_improper_fractions |
| 9 | +
|
| 10 | + >>> proper_fractions(10) |
| 11 | + ['1/10', '3/10', '7/10', '9/10'] |
| 12 | + >>> proper_fractions(5) |
| 13 | + ['1/5', '2/5', '3/5', '4/5'] |
| 14 | + >>> proper_fractions(-15) |
| 15 | + Traceback (most recent call last): |
| 16 | + ... |
| 17 | + ValueError: The Denominator Cannot be less than 0 |
| 18 | + >>> proper_fractions(0) |
| 19 | + [] |
| 20 | + >>> proper_fractions(1.2) |
| 21 | + Traceback (most recent call last): |
| 22 | + ... |
| 23 | + ValueError: The Denominator must be an integer |
| 24 | + """ |
| 25 | + |
| 26 | + if denominator < 0: |
| 27 | + raise ValueError("The Denominator Cannot be less than 0") |
| 28 | + elif isinstance(denominator, float): |
| 29 | + raise ValueError("The Denominator must be an integer") |
| 30 | + return [ |
| 31 | + f"{numerator}/{denominator}" |
| 32 | + for numerator in range(1, denominator) |
| 33 | + if gcd(numerator, denominator) == 1 |
| 34 | + ] |
| 35 | + |
| 36 | + |
| 37 | +if __name__ == "__main__": |
| 38 | + from doctest import testmod |
| 39 | + |
| 40 | + testmod() |
0 commit comments