Skip to content

Commit 49654da

Browse files
authored
Update factorial.py
1 parent 8c01da2 commit 49654da

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

dynamic_programming/factorial.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
# Factorial of a number using memoization
2-
result = [-1] * 10
3-
result[0] = result[1] = 1
42

53

64
def factorial(num):
@@ -12,26 +10,26 @@ def factorial(num):
1210
>>> [factorial(i) for i in range(5)]
1311
[1, 1, 2, 6, 24]
1412
"""
13+
result = [-1] * (num + 1)
1514

1615
if num < 0:
1716
return "Number should not be negative."
17+
18+
return factorial_aux(num, result)
19+
20+
21+
def factorial_aux(num, result):
22+
23+
if num == 0 or num == 1:
24+
return 1
25+
1826
if result[num] != -1:
1927
return result[num]
2028
else:
21-
result[num] = num * factorial(num - 1)
22-
# uncomment the following to see how recalculations are avoided
23-
# print(result)
29+
result[num] = num * factorial_aux(num - 1, result)
2430
return result[num]
2531

2632

27-
# factorial of num
28-
# uncomment the following to see how recalculations are avoided
29-
##result=[-1]*10
30-
##result[0]=result[1]=1
31-
##print(factorial(5))
32-
# print(factorial(3))
33-
# print(factorial(7))
34-
3533
if __name__ == "__main__":
3634
import doctest
3735

0 commit comments

Comments
 (0)