Skip to content

Commit 27fce12

Browse files
committed
optimizing factorial using memoization
1 parent d1a9486 commit 27fce12

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

dynamic_programming/factorial.py

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,39 @@
44

55

66
@lru_cache
7-
def factorial(num: int) -> int:
7+
def factorial(num, _memo=None):
88
"""
9+
Returns the factorial of a non-negative integer using memoization.
10+
11+
>>> factorial(0)
12+
1
13+
>>> factorial(5)
14+
120
915
>>> factorial(7)
1016
5040
1117
>>> factorial(-1)
1218
Traceback (most recent call last):
13-
...
19+
...
1420
ValueError: Number should not be negative.
1521
>>> [factorial(i) for i in range(10)]
1622
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
1723
"""
24+
if _memo is None:
25+
_memo = {}
26+
1827
if num < 0:
1928
raise ValueError("Number should not be negative.")
2029

21-
return 1 if num in (0, 1) else num * factorial(num - 1)
30+
if num in _memo:
31+
return _memo[num]
2232

33+
if num in (0, 1):
34+
_memo[num] = 1
35+
else:
36+
_memo[num] = num * factorial(num - 1, _memo)
37+
38+
return _memo[num]
2339

2440
if __name__ == "__main__":
2541
import doctest
26-
2742
doctest.testmod()

0 commit comments

Comments
 (0)