Pascal’s Triangle is a triangular arrangement of numbers where:
- The first and last number in each row is always 1.
- Each number inside the triangle is the sum of the two numbers above it.
Example of Pascal’s Triangle (First 5 Rows):
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
In this tutorial, we will learn how to generate Pascal’s Triangle using Python.
Python Program to Generate Pascal’s Triangle
Method 1: Using Loops
def pascal_triangle(n): for i in range(n): row = [1] # First element is always 1 if i > 0: for j in range(1, i): row.append(prev_row[j - 1] + prev_row[j]) # Sum of two above numbers row.append(1) # Last element is always 1 print(" ".join(str(x) for x in row).center(n * 3)) # Format output prev_row = row # Store current row for next iteration # Taking user input N = int(input("Enter the number of rows: ")) # Generating Pascal's Triangle pascal_triangle(N)
How the Program Works
- First, we define a function
pascal_triangle(n)
wheren
is the number of rows. - Next, we use a
for
loop to iterate through each row from0
ton-1
. - Every row starts with
1
because the first and last number in Pascal’s Triangle is always 1. - We create a list called
row
and set the first element as1
. - If the row has more than one element, we calculate the middle values using:
- current value = previous row’s left value+previous row’s right value
- We use a
for
loop inside to generate these values. - Each row ends with
1
, so we append1
at the end of therow
list. - We use
" ".join(str(x) for x in row).center(n * 3)
to print the row in a triangular format. - At last, we store the current row in
prev_row
so that we can use it to calculate the next row.
Output
Enter the number of rows: 5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Method 2: Using Recursion (Mathematical Approach)
We can use binomial coefficients to calculate each element:
\[ C(n, k) = \frac{n!}{k!(n-k)!} \]Where n is the row number, and k is the column index.
from math import factorial def pascal_value(n, k): return factorial(n) // (factorial(k) * factorial(n - k)) def pascal_triangle(n): for i in range(n): row = [pascal_value(i, k) for k in range(i + 1)] print(" ".join(str(x) for x in row).center(n * 3)) # Format output # Taking user input N = int(input("Enter the number of rows: ")) # Generating Pascal's Triangle pascal_triangle(N)
Comparison of Both Methods
Method | Approach | Pros | Cons |
---|---|---|---|
Loop | Builds rows iteratively | Easy to understand | Uses extra memory |
Recursion | Uses binomial coefficient formula | Efficient for smaller values | Slower for large values |