-
-
Notifications
You must be signed in to change notification settings - Fork 46.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* adding factorial * adding doctest * Update factorial.py
- Loading branch information
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
#Factorial of a number using memoization | ||
result=[-1]*10 | ||
result[0]=result[1]=1 | ||
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 | ||
doctest.testmod() |