mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
fixed error in factorial.py (#1888)
* 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>
This commit is contained in:
parent
871f8f4e00
commit
f0d7879a11
|
@ -1,36 +1,25 @@
|
|||
# Factorial of a number using memoization
|
||||
result = [-1] * 10
|
||||
result[0] = result[1] = 1
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
|
||||
def factorial(num):
|
||||
@lru_cache
|
||||
def factorial(num: int) -> int:
|
||||
"""
|
||||
>>> factorial(7)
|
||||
5040
|
||||
>>> factorial(-1)
|
||||
'Number should not be negative.'
|
||||
>>> [factorial(i) for i in range(5)]
|
||||
[1, 1, 2, 6, 24]
|
||||
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:
|
||||
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]
|
||||
raise ValueError("Number should not be negative.")
|
||||
|
||||
return 1 if num in (0, 1) else num * factorial(num - 1)
|
||||
|
||||
# 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
|
||||
|
|
Loading…
Reference in New Issue
Block a user