Skip to content

Commit 6a038a1

Browse files
authored
Update factorial.py
1 parent b7ecbf6 commit 6a038a1

File tree

1 file changed

+10
-21
lines changed

1 file changed

+10
-21
lines changed

dynamic_programming/factorial.py

Lines changed: 10 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,24 @@
11
# Factorial of a number using memoization
22

3+
from functools import lru_cache
34

5+
6+
@lru_cache
47
def factorial(num: int) -> int:
58
"""
69
>>> factorial(7)
710
5040
8-
911
>>> factorial(-1)
10-
'Number should not be negative.'
11-
12-
>>> [factorial(i) for i in range(5)]
13-
[1, 1, 2, 6, 24]
12+
Traceback (most recent call last):
13+
...
14+
ValueError: Number should not be negative.
15+
>>> [factorial(i) for i in range(10)]
16+
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
1417
"""
15-
result = [-1] * (num + 1)
16-
1718
if num < 0:
18-
return "Number should not be negative."
19-
20-
return factorial_aux(num, result)
21-
22-
23-
def factorial_aux(num, result):
24-
25-
if num == 0 or num == 1:
26-
return 1
19+
raise ValueError("Number should not be negative.")
2720

28-
if result[num] != -1:
29-
return result[num]
30-
else:
31-
result[num] = num * factorial_aux(num - 1, result)
32-
return result[num]
21+
return 1 if num in (0, 1) else num * factorial(num - 1)
3322

3423

3524
if __name__ == "__main__":

0 commit comments

Comments
 (0)