Skip to content

Commit 8f81c46

Browse files
Made improvements to combinations.py (TheAlgorithms#3681)
* Made improvements to combinations.py * Update maths/combinations.py Co-authored-by: Du Yuanchao <shellhub.me@gmail.com> * Function now raises an error when given invalid input * Update maths/combinations.py Co-authored-by: Du Yuanchao <shellhub.me@gmail.com>
1 parent 47199c1 commit 8f81c46

File tree

1 file changed

+42
-3
lines changed

1 file changed

+42
-3
lines changed

maths/combinations.py

+42-3
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,58 @@
1+
"""
2+
https://en.wikipedia.org/wiki/Combination
3+
"""
14
from math import factorial
25

36

4-
def combinations(n, k):
7+
def combinations(n: int, k: int) -> int:
58
"""
9+
Returns the number of different combinations of k length which can
10+
be made from n values, where n >= k.
11+
12+
Examples:
613
>>> combinations(10,5)
714
252
15+
816
>>> combinations(6,3)
917
20
18+
1019
>>> combinations(20,5)
1120
15504
21+
22+
>>> combinations(52, 5)
23+
2598960
24+
25+
>>> combinations(0, 0)
26+
1
27+
28+
>>> combinations(-4, -5)
29+
...
30+
Traceback (most recent call last):
31+
ValueError: Please enter positive integers for n and k where n >= k
1232
"""
33+
34+
# If either of the conditions are true, the function is being asked
35+
# to calculate a factorial of a negative number, which is not possible
36+
if n < k or k < 0:
37+
raise ValueError("Please enter positive integers for n and k where n >= k")
1338
return int(factorial(n) / ((factorial(k)) * (factorial(n - k))))
1439

1540

1641
if __name__ == "__main__":
17-
from doctest import testmod
1842

19-
testmod()
43+
print(
44+
"\nThe number of five-card hands possible from a standard",
45+
f"fifty-two card deck is: {combinations(52, 5)}",
46+
)
47+
48+
print(
49+
"\nIf a class of 40 students must be arranged into groups of",
50+
f"4 for group projects, there are {combinations(40, 4)} ways",
51+
"to arrange them.\n",
52+
)
53+
54+
print(
55+
"If 10 teams are competing in a Formula One race, there",
56+
f"are {combinations(10, 3)} ways that first, second and",
57+
"third place can be awarded.\n",
58+
)

0 commit comments

Comments
 (0)