Skip to content

optimizing factorial using memoization #12848

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions dynamic_programming/factorial.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,38 @@


@lru_cache
def factorial(num: int) -> int:
def factorial(num, _memo=None):
"""
Returns the factorial of a non-negative integer using memoization.

>>> factorial(0)
1
>>> factorial(5)
120
>>> 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 _memo is None:
_memo = {}

if num < 0:
raise ValueError("Number should not be negative.")

return 1 if num in (0, 1) else num * factorial(num - 1)
if num in _memo:
return _memo[num]

if num in (0, 1):
_memo[num] = 1
else:
_memo[num] = num * factorial(num - 1, _memo)

return _memo[num]


if __name__ == "__main__":
Expand Down
Loading