theGreatWhatever theGreatWhatever - 24 days ago 4
Python Question

Recursively generating a list of n factorial in Python

I am having trouble implementing this in Python. I want to write a function with (sole) input n, that recursively generates a list of factorial values 1! ... n!

So far I have thought of storing the recursively derived values of n-factorial in a variable, and then adding (pushing?) them into a list. The question I have is how do I 'save' the list? I am not sure how to check if a list exists or not as well...

def recFactorial(n):
if n == 1:
return 1
print(l)
else:
l = []
f = n * recFactorial(n-1)
if l:
l = l.push(f)
else:
l = []

Answer

Recursive function calls can't see the local variables of the other calls to the same function. If you want several calls to be able to work with the same list, the list needs to either be a parameter or a return value of the function (or I suppose a global variable, but that would be really bad design).

In this case, I think it would be easiest to pass the list as the return value of the function. It would be created in the base case, where you'd return the trivial list [1]. Each outer call would append a value to the list (and use the last value that was on it previously to do their calculation).

def recFactorialList(n):
    if n == 1:
        return [1]   # base case, still returns a list

    lst = recFactorialList(n-1)
    n_fac = lst[-1] * n   # use the last value to calculate a new value
    lst.append(n_fac)   # add n factorial to the end of the list
    return lst   # return the updated list