File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ #Factorial of a number using memoization
2+ result = [- 1 ]* 10
3+ result [0 ]= result [1 ]= 1
4+ def factorial (num ):
5+ """
6+ >>> factorial(7)
7+ 5040
8+ >>> factorial(-1)
9+ 'Number should not be negative.'
10+ >>> [factorial(i) for i in range(5)]
11+ [1, 1, 2, 6, 24]
12+ """
13+
14+ if num < 0 :
15+ return "Number should not be negative."
16+ if result [num ]!= - 1 :
17+ return result [num ]
18+ else :
19+ result [num ]= num * factorial (num - 1 )
20+ #uncomment the following to see how recalculations are avoided
21+ #print(result)
22+ return result [num ]
23+
24+ #factorial of num
25+ #uncomment the following to see how recalculations are avoided
26+ ##result=[-1]*10
27+ ##result[0]=result[1]=1
28+ ##print(factorial(5))
29+ # print(factorial(3))
30+ # print(factorial(7))
31+
32+ if __name__ == "__main__" :
33+ import doctest
34+ doctest .testmod ()
You can’t perform that action at this time.
0 commit comments