1

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!

  • Hi. In my opinion this question was closed erroneously by @blhsing. This question is clearly not about Pascal's triangle but about recursion and dynamic programming! The answer is to use two functions, an outer function which accumulates the rows of your triangle and an inner triangle which computes the next row. I used your code to write a sketch (which doesn't work unfortunately), see it here: https://paste.ubuntu.com/p/GXVZZKRth3/ – Johan Sjolen Sep 02 '19 at 21:27
  • The most naive way to do it is to create a supplementary function to accumulate the lists in the iteration. There must be some better way though. – 3sm1r Sep 02 '19 at 21:38
  • I was thinking about doing something like that, or memoization, but I really wanted to preserve the conciseness of the original code. Yevhen provides just the right solution below. Thanks for your comments! – panopticonopolis Sep 02 '19 at 23:55

1 Answers1

2

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]
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48