Search code examples
pythonlistrecursiontuplespascals-triangle

Attempting to generate Pascal's Triangle as a tuple using recursion


I need to write a function to generate Pascal's Triangle as a tuple using recursion.

e.g pascal(5)   
((1,), (1, 1), (1, 2, 1), (1, 3, 3, 1), (1, 4, 6, 4, 1))

I can generate it as a list with the following function:

def triangle(n):
    if n == 0:
        return []
    elif n == 1:
        return [[1]]
    else:
        new_row = [1]
        result = triangle(n-1)
        last_row = result[-1]
        for i in range(len(last_row)-1):
            new_row.append(last_row[i] + last_row[i+1])
        new_row += [1]
        result.append(new_row)
    return result

And I've tried changing this to a tuple:

def pascal(n):
    if n==0:
        return ()
    elif n==1:
        return ((1,),)
    else:
        new_row = (1,)
        result = pascal(n-1)
        last_row = result[-1]
        print(last_row)
        for i in range(len(last_row)-1):
            new_row = new_row+last_row[i]+last_row[i+1]
        new_row = new_row +(1,)
        result=result+(new_row,)
    return result

but it doesn't work and I get the error len(last_row)-1 type int has no len.

I'm not sure how to fix this code and would appreciate any help.


Solution

  • I think the problem is the result = result + new_row line.

    If you want to see why, mouseover below...

    result is a tuple of tuples, new_row is a tuple of numbers. If you add a tuple of numbers to a tuple of tuples, you end with a tuple of tuples and numbers! Such as ((1,), 1) which is not what you want. fix it by doing result = result + (new_row,)