2019-10-05 05:14:13 +00:00
|
|
|
# Factorial of a number using memoization
|
|
|
|
|
2020-08-05 11:18:41 +00:00
|
|
|
from functools import lru_cache
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2020-08-05 11:18:41 +00:00
|
|
|
|
|
|
|
@lru_cache
|
|
|
|
def factorial(num: int) -> int:
|
2019-07-17 06:22:09 +00:00
|
|
|
"""
|
|
|
|
>>> factorial(7)
|
|
|
|
5040
|
|
|
|
>>> factorial(-1)
|
2020-08-05 11:18:41 +00:00
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ValueError: Number should not be negative.
|
|
|
|
>>> [factorial(i) for i in range(10)]
|
|
|
|
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
|
2019-07-17 06:22:09 +00:00
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
if num < 0:
|
2020-08-05 11:18:41 +00:00
|
|
|
raise ValueError("Number should not be negative.")
|
2019-07-17 06:22:09 +00:00
|
|
|
|
2020-08-05 11:18:41 +00:00
|
|
|
return 1 if num in (0, 1) else num * factorial(num - 1)
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-07-17 06:22:09 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-07-17 06:22:09 +00:00
|
|
|
doctest.testmod()
|