Skip to content

Commit 8faf823

Browse files
meg-1cclausspre-commit-ci[bot]
authored
adding a proper fractions algorithm (#11224)
* adding a proper fractions algorithm * Implementing suggestions in maths/numerical_analysis/proper_fractions.py Co-authored-by: Christian Clauss <[email protected]> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Implementing suggestions to proper_fractions.py * Fixing ruff errors in proper_fractions.py * Apply suggestions from code review * ruff check --output-format=github . * Update maths/numerical_analysis/proper_fractions.py * Update proper_fractions.py --------- Co-authored-by: Christian Clauss <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 435309a commit 8faf823

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

Diff for: .github/workflows/ruff.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,4 @@ jobs:
1313
steps:
1414
- uses: actions/checkout@v4
1515
- run: pip install --user ruff
16-
- run: ruff --output-format=github .
16+
- run: ruff check --output-format=github .

Diff for: maths/numerical_analysis/proper_fractions.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

Comments
 (0)