Pascal’s Triangle Using Python

Pascal’s Triangle Using Python

ECX 30 Days of Code and Design

Day 17

Pascal’s Triangle

Task

  • Write a function that prints out the first "n" rows of Pascal's triangle. Where "n" is an integer taken as the argument of the function.
    More details.

Discussion

Pascal’s Triangle provides the coefficients used in binomial expansion. In this, we will use the combination technique which gives the same answer as Pascal’s triangle to solve the task.

$$^nC_{k} = \binom{n}{k} = \frac{n!}{k!(n-k)!}$$

CombinationCoefficients
(00)1
(10)(11)1 1
(20)(21)(22)1 2 1
(30)(31)(32)(33)1 3 3 1
(40)(41)(42)(43)(44)1 4 6 4 1

My Approach

First, we would import the math module, which would give us access to the combination function, comb. Next, we define our function, pascal_triangle, which would print out Pascal’s triangle. Next, we use the combination function starting from zero to the number inputted by the user. for num_of_elements in range(number + 1) allows us to assign the num_of_elements value from 0 to the number inputted by the user. range(number) would stop at number - 1, thus the reason number + 1 was used. for selected_elements in range(number_of_elements + 1) is used to assign selected_elements the values of num_of_elements in steps and at each step print the combination (i.e., coefficient of binomial expansion). Let's say the number 2 was inputted. Let's call num_of_elements n and selected_elements k; n is first assigned the value 0 and k is also assigned the value of 0 and their combination is found. Next, n = 1 and k = 0, their combination is found, then while n = 1, k = 1, their combination is found and a new line is printed out. Then n = 2, k = 0, and on it goes until the final combination is carried out. We ask the user for input and the function is called having the user’s input as its argument. A try except block is used to handle value error.

import math                 # For comb() [Combination] function


def pascal_triangle(numbers):
    """Prints Pascal Triangle Using Combination"""

    for num_of_elements in range(numbers + 1):
        for selected_elements in range(num_of_elements + 1):
            print(math.comb(num_of_elements, selected_elements), end=' ')

        print('\n')


print(' Pascal Triangle '.center(40, '*'))
try:
    number = int(input('Enter the range of Pascal triangle to print: '))
    pascal_triangle(number)
except ValueError:
    print('Invalid input. Enter an integer.')

Run the code on Replit.