Skip to content

Commit b736c22

Browse files
imSankocclausspre-commit-ci[bot]
authored andcommitted
Tried new TESTS for the binomial_coefficient (TheAlgorithms#10822)
* Tried new TESTS for the binomial_coefficient * Fix the tests request * Update binomial_coefficient.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update binomial_coefficient.py --------- Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent a489408 commit b736c22

File tree

1 file changed

+44
-2
lines changed

1 file changed

+44
-2
lines changed

maths/binomial_coefficient.py

+44-2
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,48 @@
11
def binomial_coefficient(n: int, r: int) -> int:
22
"""
3-
Find binomial coefficient using pascals triangle.
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).
410
511
>>> binomial_coefficient(10, 5)
612
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
741
"""
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
846
c = [0 for i in range(r + 1)]
947
# nc0 = 1
1048
c[0] = 1
@@ -17,4 +55,8 @@ def binomial_coefficient(n: int, r: int) -> int:
1755
return c[r]
1856

1957

20-
print(binomial_coefficient(n=10, r=5))
58+
if __name__ == "__main__":
59+
from doctest import testmod
60+
61+
testmod()
62+
print(binomial_coefficient(n=10, r=5))

0 commit comments

Comments
 (0)