2019-10-05 05:14:13 +00:00
|
|
|
# Factorial of a number using memoization
|
|
|
|
result = [-1] * 10
|
|
|
|
result[0] = result[1] = 1
|
|
|
|
|
|
|
|
|
2019-07-17 06:22:09 +00:00
|
|
|
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]
|
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
if num < 0:
|
2019-07-17 06:22:09 +00:00
|
|
|
return "Number should not be negative."
|
2019-10-05 05:14:13 +00:00
|
|
|
if result[num] != -1:
|
2019-07-17 06:22:09 +00:00
|
|
|
return result[num]
|
|
|
|
else:
|
2019-10-05 05:14:13 +00:00
|
|
|
result[num] = num * factorial(num - 1)
|
|
|
|
# uncomment the following to see how recalculations are avoided
|
|
|
|
# print(result)
|
2019-07-17 06:22:09 +00:00
|
|
|
return result[num]
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
# factorial of num
|
|
|
|
# uncomment the following to see how recalculations are avoided
|
2020-05-22 06:10:11 +00:00
|
|
|
# result=[-1]*10
|
|
|
|
# result[0]=result[1]=1
|
|
|
|
# print(factorial(5))
|
2019-07-17 06:22:09 +00:00
|
|
|
# print(factorial(3))
|
|
|
|
# print(factorial(7))
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-07-17 06:22:09 +00:00
|
|
|
doctest.testmod()
|