Creating a function that calculates the factorial of a number is one of the easiest recursion-related problems if you know the mathematical definition of a factorial of a number, which is as follows:
f(0) = 1
f(1) = 1
f(n) = f(n - 1) * n, n > 1
Translating this in Python is very easy, since Python is almost pseudo-code.
def f(n):
if n == 0:
return 0
if n == 1:
return 1
if n > 1:
return f(n - 1) * n
This function clearly calculates the factorial of n
, but what you really want is to calculate the factorial from 1 to n
, given a certain n
. What you can do is to have another recursive function that calls f
from 1
to n
(or from n
to 1). This function has to save the results somewhere, type in a list. Here is an option to implement such a function:
def _mf_r(n, i, a):
if i <= n:
a.append(f(i))
_mf_r(n, i + 1, a)
return a
def mf_r(n):
return _mf_r(n, 1, [])
And this is my iterative version:
def mf_i(n):
a = []
for i in range(1, n + 1):
a.append(f(i))
return a
Doing some testing
for i in range(10):
print(mf_r(i))
print(mf_i(i))
With results:
[]
[]
[1]
[1]
[1, 2]
[1, 2]
[1, 2, 6]
[1, 2, 6]
[1, 2, 6, 24]
[1, 2, 6, 24]
[1, 2, 6, 24, 120]
[1, 2, 6, 24, 120]
[1, 2, 6, 24, 120, 720]
[1, 2, 6, 24, 120, 720]
[1, 2, 6, 24, 120, 720, 5040]
[1, 2, 6, 24, 120, 720, 5040]
[1, 2, 6, 24, 120, 720, 5040, 40320]
[1, 2, 6, 24, 120, 720, 5040, 40320]
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
In the first output we have an empty list because you wanted the factorial from 1 to n
, but the tests start from 0.