MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / combinations

Function combinations

maths/combinations.py:6–41  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

4
5
6def 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
44if __name__ == "__main__":

Callers 5

combinations.pyFile · 0.70
aprioriFunction · 0.50
combination_listsFunction · 0.50
pairs_with_sumFunction · 0.50
find_triplets_with_0_sumFunction · 0.50

Calls

no outgoing calls

Tested by

no test coverage detected