Skip to content

Commit dea9684

Browse files
authored
Merge pull request #5 from PoApper/feat/bino
New exercise for recursion: Binomial Coefficient
2 parents 5c111bb + eb6cb59 commit dea9684

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
def binomial_coefficient(n, k):
2+
"""
3+
Calcaulate binomial coefficient nCk, using recursion.
4+
Hint:
5+
nCk = (n - 1)C(k - 1) + (n - 1)Ck
6+
nC0 = 1
7+
8+
>>> binomial_coefficient(1, 0)
9+
1
10+
>>> binomial_coefficient(4, 2)
11+
6
12+
>>> binomial_coefficient(4, 3)
13+
4
14+
"""
15+
if k == 0:
16+
return 1
17+
elif n <= 0 or k < 0:
18+
return 0
19+
return binomial_coefficient(n - 1, k - 1) + binomial_coefficient(n - 1, k)
20+
21+
22+
if __name__ == "__main__":
23+
import doctest
24+
25+
doctest.testmod(verbose=True)
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
def binomial_coefficient(n, k):
2+
"""
3+
Calcaulate binomial coefficient nCk, using recursion.
4+
Hint:
5+
nCk = (n - 1)C(k - 1) + (n - 1)Ck
6+
nC0 = 1
7+
8+
>>> binomial_coefficient(1, 0)
9+
1
10+
>>> binomial_coefficient(4, 2)
11+
6
12+
>>> binomial_coefficient(4, 3)
13+
4
14+
"""
15+
pass
16+
17+
18+
if __name__ == "__main__":
19+
import doctest
20+
21+
doctest.testmod(verbose=True)

04-functions-modules/guide.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,11 @@
66
- background: list, iteration
77

88
Implement `min`, `max` functions on your own.
9+
10+
## Binomial Coefficient
11+
12+
- difficulty: ★★☆
13+
- time: ~ 30m for beginners
14+
- background: function, recursion
15+
16+
Implement a function which calculates binomial coefficient, $\prescript{}{n}C_k$.

0 commit comments

Comments
 (0)