How to Create a Pascal Triangle in Python?

Estimated read time 2 min read

You can create a Pascal triangle in Python using a nested loop and some basic arithmetic. Here’s an example code that generates the first n rows of Pascal’s triangle:

def pascal_triangle(n):
    triangle = []
    for i in range(n):
        row = [1] * (i + 1)
        for j in range(1, i):
            row[j] = triangle[i-1][j-1] + triangle[i-1][j]
    return triangle

In this code, the pascal_triangle() function takes a single argument n which is the number of rows of the triangle to generate. The function initializes an empty list triangle to store the rows of the triangle.

The function then uses a nested loop to generate each row of the triangle. For each row, it first creates a list row of length i+1 filled with 1’s. It then uses another loop to calculate the values of the non-edge elements in the row, which are the sum of the corresponding elements from the previous row. Finally, the completed row is added to the triangle list.

After all rows have been generated, the triangle list is returned.

You can call this function and pass in a value of n to generate the first n rows of Pascal’s triangle, like this:

n = 5
triangle = pascal_triangle(n)
for row in triangle:

In this code, we set n to 5 and then call the pascal_triangle() function with this value. The resulting triangle is then printed to the console row by row.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply