forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinomial_coefficient.py
62 lines (56 loc) · 1.65 KB
/
binomial_coefficient.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
defbinomial_coefficient(n: int, r: int) ->int:
"""
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_coefficient(10, 0)
1
>>> binomial_coefficient(0, 10)
1
>>> binomial_coefficient(10, 10)
1
>>> binomial_coefficient(5, 2)
10
>>> binomial_coefficient(5, 6)
0
>>> binomial_coefficient(3, 5)
0
>>> binomial_coefficient(-2, 3)
Traceback (most recent call last):
...
ValueError: n and r must be non-negative integers
>>> binomial_coefficient(5, -1)
Traceback (most recent call last):
...
ValueError: n and r must be non-negative integers
>>> binomial_coefficient(10.1, 5)
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
>>> binomial_coefficient(10, 5.1)
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
"""
ifn<0orr<0:
raiseValueError("n and r must be non-negative integers")
if0in (n, r):
return1
c= [0foriinrange(r+1)]
# nc0 = 1
c[0] =1
foriinrange(1, n+1):
# to compute current row from previous row.
j=min(i, r)
whilej>0:
c[j] +=c[j-1]
j-=1
returnc[r]
if__name__=="__main__":
fromdoctestimporttestmod
testmod()
print(binomial_coefficient(n=10, r=5))