forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added combination_memo.py using memoization (keon#358)
* Update combination.py * Update test_maths.py * fixed test_maths.py * update function combination_memo * update test of combination_memo
- Loading branch information
1 parent
7cbe6e1
commit 37bee74
Showing
2 changed files
with
16 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,17 @@ | ||
def combination(n, r): | ||
# This function calculates nCr | ||
"""This function calculates nCr.""" | ||
if n == r or r == 0: | ||
return 1 | ||
else: | ||
return combination(n-1, r-1) + combination(n-1, r) | ||
|
||
def combination_memo(n, r): | ||
"""This function calculates nCr using memoization method.""" | ||
memo = {} | ||
def recur(n, r): | ||
if n == r or r == 0: | ||
return 1 | ||
if (n, r) not in memo: | ||
memo[(n, r)] = recur(n - 1, r - 1) + recur(n - 1, r) | ||
return memo[(n, r)] | ||
return recur(n, r) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters