Search code examples
pythonlistrecursionpascals-triangle

How to grow and return a list from inside a recursive function in python


I have a recursive solution to Pascal's triangle, but it returns the row of the triangle requested, and not all of the rows preceding it. I would like to know if there is a way to scoop up all the rows as they are computed from the base case and down the call stack, and return that as a list.

Writing the recursion for computing/returning any given row wasn't difficult but I thought I could just append each return to a list variable. The issue I'm having is anything I do to return the whole list messes with the return statement and breaks the computation of the row.

def pascal(n, tri):
    if n == 0:
        return tri
    else:
        r = pascal(n - 1, tri)
        row = [1] + [(r[i] + r[i + 1]) for i in range(len(r) - 1)] + [1]
        tri.append(row)
        print('tri =', tri)
    return tri[-1]

print(pascal(5, [[1]]))

The print statement inside the function shows that the rows get appended to the list. I just can't think of how to return the list outside the function. I need the last list element of 'tri' to generate the next layer, but at the same time I want to return all of 'tri' as my final return.

This is my first SO question so apologies if I'm just not seeing something blindingly obvious here. Thank you!


Solution

  • You should return the whole tri and use only the last element of r when you build a row:

    row = [1] + [(r[-1][i] + r[-1][i + 1]) for i in range(len(r[-1]) - 1)] + [1]