Creating a function that calculates the factorial of a number is one of the easiest recursion-related problems if you know the mathematical factorial definition of a number, which is the following:
f(0) = 1
f(1) = 1
f(n) = f(n - 1) * n, n > 1
Translating this into 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 factor of n
, but what you really want is to calculate the factor of 1 until n
, given a certain n
. What you can do is have another recursive function that calls f
starting from 1
until n
(or of n
up to 1). This function has to save the results somewhere, like 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
Running some tests
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 of 1 until n
, but the tests start from 0.
Dude, if this is a college exercise in programming logic, make an effort to.
– Puam Dias
But I can’t do it... so I’m asking for help.
– CSAnimor
This kind of question devalues the site
– sergiopereira