Skip to content

fixed error in factorial.py #1888

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

Merged
merged 5 commits into from
Aug 5, 2020
Merged
Changes from 1 commit
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
24 changes: 11 additions & 13 deletions dynamic_programming/factorial.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# Factorial of a number using memoization
result = [-1] * 10
result[0] = result[1] = 1


def factorial(num):
Expand All @@ -12,26 +10,26 @@ def factorial(num):
>>> [factorial(i) for i in range(5)]
[1, 1, 2, 6, 24]
"""
result = [-1] * (num + 1)

if num < 0:
return "Number should not be negative."

return factorial_aux(num, result)


def factorial_aux(num, result):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Type hints? Doctests?


if num == 0 or num == 1:
return 1

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)
result[num] = num * factorial_aux(num - 1, result)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Technically, this is more of a "memoization" approach. While being perfectly correct, the more appropriate algorithm for this section may look as follows

Suggested change
result[num] = num * factorial_aux(num - 1, result)
result[0] = 1
for i in xrange(num):
result.append((i + 1) * result[i])
return result[num]

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

xrange() was removed from Python on 1/1/2020.

The canonical way to do memoization in Python is with the lru_cache function decorator.

return result[num]


# 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

Expand Down