mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-24 13:31:07 +00:00
f0d7879a11
* Update factorial.py * updating DIRECTORY.md * Update dynamic_programming/factorial.py * Update factorial.py Co-authored-by: mateuszz0000 <mtszzwdzk@gmail.com> Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
28 lines
585 B
Python
28 lines
585 B
Python
# Factorial of a number using memoization
|
|
|
|
from functools import lru_cache
|
|
|
|
|
|
@lru_cache
|
|
def factorial(num: int) -> int:
|
|
"""
|
|
>>> factorial(7)
|
|
5040
|
|
>>> factorial(-1)
|
|
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]
|
|
"""
|
|
if num < 0:
|
|
raise ValueError("Number should not be negative.")
|
|
|
|
return 1 if num in (0, 1) else num * factorial(num - 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import doctest
|
|
|
|
doctest.testmod()
|