Search code examples
pythonarrayslistmathpascals-triangle

Pascal's triangle in Python with 2-D Arrays


I'm trying write a python code that iterates over a 2-D array, the outer list should have rows in it and the inner lists should have the elements for the numbers in Pascal's triangle. I believe I'm running into issues with initializing the lists, It's been a while since I wrote in Python so any help would be appreciated.

I tried writing my code using this image
https://www.mathsisfun.com/images/pascals-triangle-n-choose-k.gif

from math import factorial

def binomial(x, y):
    try:
        return factorial(x) / (factorial(y) * factorial(x - y))
    except ValueError:
        return 0


def pascals_triangle(number_of_rows):
    triangle = []
    if number_of_rows <= 0:
        return None
    else:
        for row in range(number_of_rows+1):
            for column in range(row+1):
                triangle[row][column] = (binomial(row, column))
    return triangle

print(pascals_triangle(1))

Solution

  • You are treating triangle as if it's a 2D list, but it's not, and that's why you get the error. Try replacing your function with this:

    def pascals_triangle(number_of_rows):
        triangle = []
        if number_of_rows <= 0:
            return None
        else:
            for row in range(number_of_rows+1):
                triangle.append([binomial(row, column) for column in range(row+1)])
        return triangle