Search code examples
pythonrecursionpascals-triangle

python last row recursive pascal triangle


I have to create a recursive function pascal(n) that returns the line n of a pascal triangle as a list (so pascal(3) returns [1, 3, 3, 1]).

So far I have

def pascal(n):

    if n==1: 
        return [[1]]
    else:
        result=pascal(n-1)
        row=[1]
        last_row=result[-1]
        for i in range(len(last_row)-1):
            row.append(last_row[i]+last_row[i+1])
        row+=[1]
        result.append(row)
        return row

But this results in the error

object of type 'int' has no len()

If i instead write

def pascal(n):

    if n==1: 
        return [[1]]
    else:
        result=pascal(n-1)
        row=[1]
        last_row=result[-1]
        for i in range(len(last_row)-1):
            row.append(last_row[i]+last_row[i+1])
        row+=[1]
        result.append(row)
        return result

And then call pascal(3)[-1], there is no problem. How can I fix this issue? Thanks.


Solution

  • You want pascal(n) to return the nth line of the Pascals triangle as a list, but you are returning [[1]] instead of [1] for pascal(1).

    Also, the "last_row", i.e the previous row corresponding to pascal(n) would be pascal(n-1) and not pascal(n-1)[-1]. In your code, result[-1] is pascal(n-1)[-1] which the last element (int) of the (n-1)th row, hence the error.

    This would be your function after making the above 2 changes.

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