Search code examples
pythonrecursionpascals-triangle

Recursion Pascal's Triangle (Python)


I'm not sure what I'm doing wrong with my code here in getting a recursive pascal's triangle to work in python. Any help is kindly appreciated :)

n = 5
def printPascal(n):
    Pascal_List = []
    if n == 0:
        Pascal_List.append([1])
        return Pascal_List
    if n == 1:
        Pascal_List.append([1])
        Pascal_List.append([1,1])
        return Pascal_List


    else:

        new_row = [1]
        final_r = printPascal(n - 1)
        last_row = final_r[-1]
        for k in range(1, last_row[-1]):
            new_row.append(final_r[k] + final_r[k - 1])

        new_row += last_row
        final_r.append(new_row)
        return final_r

print(printPascal(n))

Solution

  • You've made a few confusions in the loop that builds a new line. range(1, last_row[-1]) doesn't really make sense; you want to iterate over the indices of the last row, ie range(len(last_row)). You've also mixed up final_r and last_row on the next line.

    Here is a corrected version of your code :

    n = 5
    
    def printPascal(n):
        Pascal_List = []
        if n == 0:
            Pascal_List.append([1])
            return Pascal_List
    
        if n == 1:
            Pascal_List.append([1])
            Pascal_List.append([1,1])
            return Pascal_List
    
        else:
            new_row = [1]
            final_r = printPascal(n - 1)
            last_row = final_r[-1]
            for k in range(len(last_row)-1):
                new_row.append(last_row[k] + last_row[k + 1])
            new_row.append(1)
    
            final_r.append(new_row)
            return final_r
    
    print(printPascal(n))