|
| 1 | +""" |
| 2 | +https://en.wikipedia.org/wiki/Combination |
| 3 | +""" |
1 | 4 | from math import factorial
|
2 | 5 |
|
3 | 6 |
|
4 |
| -def combinations(n, k): |
| 7 | +def combinations(n: int, k: int) -> int: |
5 | 8 | """
|
| 9 | + Returns the number of different combinations of k length which can |
| 10 | + be made from n values, where n >= k. |
| 11 | +
|
| 12 | + Examples: |
6 | 13 | >>> combinations(10,5)
|
7 | 14 | 252
|
| 15 | +
|
8 | 16 | >>> combinations(6,3)
|
9 | 17 | 20
|
| 18 | +
|
10 | 19 | >>> combinations(20,5)
|
11 | 20 | 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 |
12 | 32 | """
|
| 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") |
13 | 38 | return int(factorial(n) / ((factorial(k)) * (factorial(n - k))))
|
14 | 39 |
|
15 | 40 |
|
16 | 41 | if __name__ == "__main__":
|
17 |
| - from doctest import testmod |
18 | 42 |
|
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