Instagram
youtube
Facebook
Twitter

Pascal's Triangle in Python

    A Pascal's Triangle in Python

    
     Short Description:
     
This program generates Pascal's Triangle using the concept of combinations (nCr).
     Each number is the sum of the two numbers directly above it in the previous row.

     Explanation (in dot points):

  • factorial(n)
    • A helper function to calculate factorial of n.

     
  • pascal_triangle(rows)
    • Loops through each row to build the triangle.

     
  • value = factorial(i) // (factorial(k) * factorial(i - k))
    • Calculates each element using the combinatorics formula:
    nCr=n!r!(n−r)!\text{nCr} = \frac{n!}{r!(n - r)!}nCr=r!(n−r)!n!​
  • print(" ", end="")
    • Adds spacing before numbers for a triangular shape.

     
  • print(value, end=" ")
    • Prints each value followed by a space on the same line.

Program:

def factorial(n):

    if n == 0 or n == 1:

        return 1

    return n * factorial(n - 1)

def pascal_triangle(rows):

    for i in range(rows):

        for j in range(rows - i - 1):

            print(" ", end="")  

        for k in range(i + 1):

            value = factorial(i) // (factorial(k) * factorial(i - k))

            print(value, end=" ")

        print()

n = int(input("Enter number of rows: "))