MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / binomial_coefficient

Function binomial_coefficient

maths/binomial_coefficient.py:1–55  ·  view source on GitHub ↗

Find binomial coefficient using Pascal's triangle. Calculate C(n, r) using Pascal's triangle. :param n: The total number of items. :param r: The number of items to choose. :return: The binomial coefficient C(n, r). >>> binomial_coefficient(10, 5) 252 >>> binomial_

(n: int, r: int)

Source from the content-addressed store, hash-verified

1def binomial_coefficient(n: int, r: int) -> int:
2 """
3 Find binomial coefficient using Pascal's triangle.
4
5 Calculate C(n, r) using Pascal's triangle.
6
7 :param n: The total number of items.
8 :param r: The number of items to choose.
9 :return: The binomial coefficient C(n, r).
10
11 >>> binomial_coefficient(10, 5)
12 252
13 >>> binomial_coefficient(10, 0)
14 1
15 >>> binomial_coefficient(0, 10)
16 1
17 >>> binomial_coefficient(10, 10)
18 1
19 >>> binomial_coefficient(5, 2)
20 10
21 >>> binomial_coefficient(5, 6)
22 0
23 >>> binomial_coefficient(3, 5)
24 0
25 >>> binomial_coefficient(-2, 3)
26 Traceback (most recent call last):
27 ...
28 ValueError: n and r must be non-negative integers
29 >>> binomial_coefficient(5, -1)
30 Traceback (most recent call last):
31 ...
32 ValueError: n and r must be non-negative integers
33 >>> binomial_coefficient(10.1, 5)
34 Traceback (most recent call last):
35 ...
36 TypeError: 'float' object cannot be interpreted as an integer
37 >>> binomial_coefficient(10, 5.1)
38 Traceback (most recent call last):
39 ...
40 TypeError: 'float' object cannot be interpreted as an integer
41 """
42 if n < 0 or r < 0:
43 raise ValueError("n and r must be non-negative integers")
44 if 0 in (n, r):
45 return 1
46 c = [0 for i in range(r + 1)]
47 # nc0 = 1
48 c[0] = 1
49 for i in range(1, n + 1):
50 # to compute current row from previous row.
51 j = min(i, r)
52 while j > 0:
53 c[j] += c[j - 1]
54 j -= 1
55 return c[r]
56
57
58if __name__ == "__main__":

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected