From f195d9251cc64adb64549f79f4e774e220a668ab Mon Sep 17 00:00:00 2001 From: Jigyasa G <33327397+jpg-130@users.noreply.github.com> Date: Wed, 17 Jul 2019 11:52:09 +0530 Subject: [PATCH] adding factorial (#930) * adding factorial * adding doctest * Update factorial.py --- dynamic_programming/factorial.py | 34 ++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 dynamic_programming/factorial.py diff --git a/dynamic_programming/factorial.py b/dynamic_programming/factorial.py new file mode 100644 index 000000000..7c6541ee2 --- /dev/null +++ b/dynamic_programming/factorial.py @@ -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()