forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactorial.py
More file actions
34 lines (31 loc) · 813 Bytes
/
factorial.py
File metadata and controls
34 lines (31 loc) · 813 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#Factorial of a number using memoization
result=[-1]*10
result[0]=result[1]=1
def factorial(num):
"""
>>> factorial(7)
5040
>>> factorial(-1)
'Number should not be negative.'
>>> [factorial(i) for i in range(5)]
[1, 1, 2, 6, 24]
"""
if num<0:
return "Number should not be negative."
if result[num]!=-1:
return result[num]
else:
result[num]=num*factorial(num-1)
#uncomment the following to see how recalculations are avoided
#print(result)
return result[num]
#factorial of num
#uncomment the following to see how recalculations are avoided
##result=[-1]*10
##result[0]=result[1]=1
##print(factorial(5))
# print(factorial(3))
# print(factorial(7))
if __name__ == "__main__":
import doctest
doctest.testmod()