Python Program for Pascal's Triangle

1. Introduction

Pascal's Triangle is a triangular array of binomial coefficients with applications in mathematics, combinatorics, and computer science. Each row represents the coefficients of the binomial expansion. Writing a Python program to print Pascal's Triangle introduces concepts such as loops and lists in a practical, visually appealing way.

2. Program Steps

1. Ask the user for the number of rows of Pascal's Triangle to print.

2. Use a function to generate Pascal's Triangle using a list of lists.

3. Print Pascal's Triangle, formatting the output for proper alignment.

3. Code Program

# Function to generate Pascal's Triangle
def generate_pascals_triangle(rows):
    triangle = []
    for i in range(rows):
        row = [None for _ in range(i + 1)]
        row[0], row[-1] = 1, 1  # First and last values in each row are 1
        # Calculate intermediate values
        for j in range(1, len(row) - 1):
            row[j] = triangle[i-1][j-1] + triangle[i-1][j]
        triangle.append(row)
    return triangle

# Function to print Pascal's Triangle
def print_triangle(triangle):
    for row in triangle:
        print(' '.join(map(str, row)).center(2*len(triangle)))

# Main program
if __name__ == "__main__":
    rows = int(input("Enter the number of rows: "))
    triangle = generate_pascals_triangle(rows)
    print_triangle(triangle)

Output:

Enter the number of rows: 5
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

Explanation:

1. The program defines a function generate_pascals_triangle that creates Pascal's Triangle up to a specified number of rows. It uses a list to store each row as a list of integers.

2. Inside this function, a loop iterates for the number of rows, creating a new list row for each row of the triangle. The first and last elements of each row are set to 1.

3. A nested loop calculates the values of the intermediate positions in each row (not the first or last), which are the sum of the two numbers directly above in the previous row.

4. The print_triangle function takes the generated list of lists (the triangle) and prints each row, formatted to be centered based on the triangle's width.

5. The main block of the program prompts the user to enter the number of rows, generates Pascal's Triangle using the generate_pascals_triangle function, and prints it using the print_triangle function.

6. This approach demonstrates the use of nested loops, list comprehension, and string formatting to generate and display Pascal's Triangle in Python.


Comments