×

Python Pascal Triangle

Python Pascal Triangle

Pascal triangle

A pascal triangle is a number pattern of triangular array of the binomial coefficients. For designing a pascal triangle, we write a function in the program which takes an integer value as the input and print the number of lines (given by user as the integer value) for the pascal triangle.

Example: Following is the example of a pascal triangle pattern with the first 6 rows:

 1
 1 1
 1 2 1
 1 3 3 1
 1 4 6 4 1
 1 5 10 10 5 1 

Pascal triangle in Python

In Python, we draw the pascal triangle pattern using the math module. We use the factorial functions of the math module in our Python program to implement the nCr formula for pascal triangle.

Here, in this tutorial, we will learn about the following methods in our Python program to get the pascal triangle pattern in the output:

1). Directly implementing nCr formula

2). Using C (line, m-1) implementation

3). Using powers of 11 implementation

Let's learn about the all the above given methods details and understand them with an example program.

Method 1: Directly implementing the nCr Formula in the program:

When we use the nCr formula in our program, a pictorial representation as given below will appear on the screen:

           ?C0

        ¹C0   ¹C1

2C02C12C2

3C03C13C23C3

We will use the following steps or algorithm in the program while implementing this method:

  • We will first take an input integer which is the number of rows of pascal triangle to be printed. Let's assume this input integer as 'num'.
  • We will make outer iteration of m variable from 0 to given num times, for printing the rows of triangle.
  • Then, we will make inner iteration of variable n from 0 to (num-1) times, for printing variables in each row.
  • After that, we will print single blank space as " ".
  • Then, we will close the inner loop (n variable loop) and it will create the left spacing in the rows.
  • After that, we will make an inner iteration for the n variable from 0 to m.
  • Then, we will print the nCr result for m and n.
  • Now, we will close the inner loop of program.
  • In last, we will print or add new line after each inner iteration of n loop. It will add a new line while printing a new row.

Now, look at the following program for the implementation of above algorithm:

Example –

 # importing factorial functions from math module
 from math import factorial
 # taking number of rows as input from user
 num = int (input ("Enter the number of rows for pascal triangle: "))
 # defining the outer iteration for number of loops
 for m in range(num):
         # defining inner iteration for variables in each row
             for n in range(num-m+1):
                         # closing inner n iteration for left spacing
                         print (end=" ")
         # inner n iteration for elements of pascal triangle
             for n in range(m+1):
                         # implementing the nCr = n!/((n-r)!*r!) formula
                         print (factorial(m)//(factorial(n)*factorial(m-n)), end=" ")
             # using print statement for new line
             print () 

Output:

 Enter the number of rows for pascal triangle: 6
        1
       1 1
      1 2 1
     1 3 3 1
    1 4 6 4 1
   1 5 10 10 5 1
 The time complexity for the pascal triangle we have printed above is O(N²). 

Method 2: Using C (line, m-1) implementation:

In this method, we will learn that how we can optimize the complexity of code given in method 1. In this method, we will follow the concept of binomial coefficients i.e., the mth entry in a given line number (let's say line) is the binomial coefficient for C (line, m). And, all the lines of pascal triangle will start with the value 1.

The basic idea used in this implementation is that we have to calculate the C (line, m) binomial coefficients using the C (line, m-1) coefficient. General formula for such type of implementation is as follows:

C (line, m) = [C (line, m-1) * (line - m + 1)]/ m

Now, look at the following program for the implementation of above given method:

Example – 

 # taking number of rows as input from user
 num = int (input ("Enter the number of rows for pascal triangle: "))
 # defining for loop for number of rows
 for m in range(1, num+1):
 # using inner iteration for elements in triangle rows
 for n in range(0, num-m+1):
         # for left spacing in rows
 print (' ', end='')
 # defining C as first element of array equals to 1
     C = 1
     # using for loop for values in line
 for n in range(1, m+1):
         # the first value in a line is always equals to 1
 print (' ', C, sep='', end='')
      # using Binomial Coefficient for C variable
         C = C * (m - n) // n
 # printing new line for each row
 print() 

Output:

Enter the number of rows for pascal triangle: 7         
         1
        1 1
       1 2 1
      1 3 3 1
     1 4 6 4 1
    1 5 10 10 5 1
   1 6 15 20 15 6 1
 The time complexity for the pascal triangle we have printed above is O(N²). 

Method 3: Using powers of 11 implementation:

This method is considered as the most optimized approach for printing pascal triangle pattern in Python. This method is based on the approach of powers of 11. Look at the following powers of 11 to understand this approach:

 11? = 1
 11¹ = 11
 11² = 121
 11³ = 1331 etc. 

Note: However, this approach is only limited up to the n = 5 i.e., 11?. It means we cannot print more than 5 rows of pascal triangle using this approach.

Now, look at the following program for the implementation of above given approach:

Example – 1

 # taking number of rows as input from user
 num = int (input ("Enter the number of rows for pascal triangle (Maximum 5): "))
 # using for loop for number of rows
 for a in range(num):
     # adjust left spacing between each element
 print (' '*(num-a), end='')
     # computing power of 11 for each row
 print(' '.join(map(str, str(11**a)))) 

Output:

 Enter the number of rows for pascal triangle (Maximum 5): 5
      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1
 The time complexity for the pascal triangle we have printed above is O(N). 

Related Topics

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

Python data science course

What is meant by Data Science? When processing raw, structured, and unstructured data utilizing various technologies, algorithms, and the scientific method, data science is a detailed study of the enormous quantity...

4 minutes read.

Multiprocessing in python

The word multiprocessing is used to compute the operation in which more than two processors run simultaneously with more than one central processor. The computer's performance increases gradually. Multiprocessing is...

6 minutes read.

Python Random Module

The tutorial for the Python random module demonstrates how to produce pseudo-random integers in Python. Random Number Generator (RNG) The RNG (random number generator) generates a series of values with no discernible...

8 minutes read.

Python Function

Python Function A Python function is a reusable, organized block of code that is used to perform the specific task. The functions are the appropriate way to divide an extensive program into a...

7 minutes read.

How to Import Files in Python

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

Covariance in Python

Covariance is defined as the estimate of the difference of change between two variables or more variables. It defines the changes of two variables together. In Python, The covariance can...

2 minutes read.

Python Switch Case

What is a Switch Case Statement? In the programming languages, a switch statement is a logical loop or syntax that tests the variable's value and compares it with multiple cases. Once...

3 minutes read.

Difference between Mutable and Immutable Objects

Difference between Mutable and Immutable Objects As we all know that Python is an object-oriented programming language. Object-oriented programming approach is based on the objects and the classes’ stores the data...

4 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

Python Knapsack problem

Python Knapsack problem Before we dig down about Knapsack problems in Python, first let's have a look at what is actually a knapsack problem. What is a knapsack problem? A problem from the...

5 minutes read.

Python String isalnum() method

Python String isalnum() method The string.isalnum () method in Python returns a boolean value true if all characters in the string are alphanumeric else for any other value it returns false. Syntax String.isalnum() Parameter NA Return This...

1 minute read.

Import Module in Python

In this article, you will learn everything about “ Import ” in Python. Modules in python that are already created can be accessed and used in another code by importing the...

6 minutes read.

Best Python AI Projects

Artificial consciousness is advancing quickly, from Chabot's to self-driving vehicles. Because of the various advantages and development presented by AI, numerous enterprises have begun searching for AI-fueled applications. Thus, there...

7 minutes read.

Python Prime factorization

Python Prime factorization In this tutorial, we will design a program where we will find all the prime factors of a number. Then, we will print all these prime factors of...

3 minutes read.

Is Python Case-sensitive when Dealing with Identifiers

Yes, Python is a case-sensitive language while dealing with identifiers. Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. It is a case-sensitive...

6 minutes read.