Skip to content

adding factorial #930

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 3 commits into from
Jul 17, 2019
Merged
Changes from 2 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
35 changes: 35 additions & 0 deletions dynamic_programming/factorial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#Factorial of a number using memoization
def factorial(num):
"""
>>> factorial(7)
5040
>>> factorial(-1)
'Number should not be negative.'
>>> [factorial(i) for i in range(5)]
[1, 1, 2, 6, 24]
"""

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]

#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
result=[-1]*10
result[0]=result[1]=1
Copy link
Member

Choose a reason for hiding this comment

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

Hint: Move lines 33 and 34 inside the factorial() function.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ok but if I do that the values are recomputed every time the function is called i.e. I don't want to recompute 3! if 7! is already computed.

Copy link
Member

@cclauss cclauss Jul 16, 2019

Choose a reason for hiding this comment

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

Understood. Then put those two lines at the top of the file at global scope before the function and the main()

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thank You!

doctest.testmod()