Skip to content

Commit 37bee74

Browse files
arsgsg1goswami-rahul
authored andcommitted
added combination_memo.py using memoization (#358)
* Update combination.py * Update test_maths.py * fixed test_maths.py * update function combination_memo * update test of combination_memo
1 parent 7cbe6e1 commit 37bee74

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

algorithms/maths/combination.py

+12-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,17 @@
11
def combination(n, r):
2-
# This function calculates nCr
2+
"""This function calculates nCr."""
33
if n == r or r == 0:
44
return 1
55
else:
66
return combination(n-1, r-1) + combination(n-1, r)
7+
8+
def combination_memo(n, r):
9+
"""This function calculates nCr using memoization method."""
10+
memo = {}
11+
def recur(n, r):
12+
if n == r or r == 0:
13+
return 1
14+
if (n, r) not in memo:
15+
memo[(n, r)] = recur(n - 1, r - 1) + recur(n - 1, r)
16+
return memo[(n, r)]
17+
return recur(n, r)

tests/test_maths.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
pythagoras,
1313
is_prime,
1414
encrypt, decrypt, generate_key,
15-
combination
15+
combination, combination_memo
1616
)
1717

1818
import unittest
@@ -230,7 +230,9 @@ class TestCombination(unittest.TestCase):
230230
def test_combination(self):
231231
self.assertEqual(10, combination(5, 2))
232232
self.assertEqual(252, combination(10, 5))
233-
233+
def test_combination_memo(self):
234+
self.assertEqual(10272278170, combination_memo(50, 10))
235+
self.assertEqual(847660528, combination_memo(40, 10))
234236
class TestFactorial(unittest.TestCase):
235237
"""[summary]
236238
Test for the file factorial.py

0 commit comments

Comments
 (0)