+ 2
How to do factorial in python
3 ответов
+ 6
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
Or you can use the factorial() function from the math module
from math import factorial
+ 2
No recursion needed:
x = 1
for i in range(1, 5):
x *= i
print(x)
#120
+ 1
I would add to the answer above memoization by adding an array that store factorials already found.