File tree Expand file tree Collapse file tree 1 file changed +11
-13
lines changed Expand file tree Collapse file tree 1 file changed +11
-13
lines changed Original file line number Diff line number Diff line change 1
1
# Factorial of a number using memoization
2
- result = [- 1 ] * 10
3
- result [0 ] = result [1 ] = 1
4
2
5
3
6
4
def factorial (num ):
@@ -12,26 +10,26 @@ def factorial(num):
12
10
>>> [factorial(i) for i in range(5)]
13
11
[1, 1, 2, 6, 24]
14
12
"""
13
+ result = [- 1 ] * (num + 1 )
15
14
16
15
if num < 0 :
17
16
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
+
18
26
if result [num ] != - 1 :
19
27
return result [num ]
20
28
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 )
24
30
return result [num ]
25
31
26
32
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
-
35
33
if __name__ == "__main__" :
36
34
import doctest
37
35
You can’t perform that action at this time.
0 commit comments