Returns the number of different combinations of k length which can be made from n values, where n >= k. Examples: >>> combinations(10,5) 252 >>> combinations(6,3) 20 >>> combinations(20,5) 15504 >>> combinations(52, 5) 2598960 >>> combinations(0,
(n: int, k: int)
| 4 | |
| 5 | |
| 6 | def combinations(n: int, k: int) -> int: |
| 7 | """ |
| 8 | Returns the number of different combinations of k length which can |
| 9 | be made from n values, where n >= k. |
| 10 | |
| 11 | Examples: |
| 12 | >>> combinations(10,5) |
| 13 | 252 |
| 14 | |
| 15 | >>> combinations(6,3) |
| 16 | 20 |
| 17 | |
| 18 | >>> combinations(20,5) |
| 19 | 15504 |
| 20 | |
| 21 | >>> combinations(52, 5) |
| 22 | 2598960 |
| 23 | |
| 24 | >>> combinations(0, 0) |
| 25 | 1 |
| 26 | |
| 27 | >>> combinations(-4, -5) |
| 28 | ... |
| 29 | Traceback (most recent call last): |
| 30 | ValueError: Please enter positive integers for n and k where n >= k |
| 31 | """ |
| 32 | |
| 33 | # If either of the conditions are true, the function is being asked |
| 34 | # to calculate a factorial of a negative number, which is not possible |
| 35 | if n < k or k < 0: |
| 36 | raise ValueError("Please enter positive integers for n and k where n >= k") |
| 37 | res = 1 |
| 38 | for i in range(k): |
| 39 | res *= n - i |
| 40 | res //= i + 1 |
| 41 | return res |
| 42 | |
| 43 | |
| 44 | if __name__ == "__main__": |
no outgoing calls
no test coverage detected