×

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 String islower() method

Python String islower() method The string.islower() method returns a boolean value true if all cased characters in the string are lowercase and for  any other value is returns false otherwise. Syntax string.islower() Parameter NA Return This...

1 minute read.

Python Tuple index() Method

Python Tuple index() Method The tuple.index() method of Python finds the first occurrence of the specified value and returns its index if the value is found else raises an exception if...

1 minute read.

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In...

5 minutes read.

Python Dictionary update() method

Python Dictionary update() method The dictionary.update() method in Python inserts the specified items to the dictionary. Syntax dictionary.update(iterable) Parameter iterable- This parameter represents a dictionary or an iterable object with key value pairs, that will...

1 minute read.

How to Install PIP In Python

How to Install PIP In Python The libraries for Python have made our work easier than we expected. From a simple addition of two numbers to applying algorithms on the big...

4 minutes read.

Python Program to Check Leap Year

Python Program to Check Leap Year Leap year: We all know that each year has 365 or 366 days. But whenever a year has 366 days, then the year is said...

2 minutes read.

Application to Search Installed Application using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

Python Syntax

Python is a strong object-oriented programming language that is simple to learn. Python was created to be a very readable programming language. The syntax of the Python programming language is...

8 minutes read.

Best resources to learn Numpy and Pandas in python

In this tutorial, we will discuss the different resources where we can learn about NumPy and Pandas libraries of Python in a more efficient way. NumPy NumPy, a Python library used for...

4 minutes read.

Classes & Objects in Python

Classes and Objects are used in most modern programming languages, mainly in Object-oriented Programming languages. What is meant by Object Oriented Programming language? Usage of objects and their components in order to...

7 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.

Python while loop

Loops are essential in Python or any other programming language, as they help to execute a block of code repetitively. Sometimes, situations arise where you would need to use a piece of code...

2 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Python Program to Print Sum of all Elements in an Array

Python program to print sum of all elements in an array A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep...

2 minutes read.

Python Maurer Rose and Rhodonea Curves

In this tutorial, in Python we will make a Maurer Rose example and Rhodonea Curve example. Before we continue to see what precisely is maurer rose or a rhodonea bend...

10 minutes read.

Python logging Module

Python logging Module Introduction By logging word we understand the tracking of the events which happens when we run some software. Logging process is very important part for developing software, debugging...

12 minutes read.

Python Identifiers

Identifiers in Python User-defined names are identifiers in Python that are used to name variables, functions, classes, modules, and other things. You can create Python identifiers using these rules: As an identifier...

4 minutes read.

Alexa Python

The cloud-based voice assistant renders text into speech in a female voice. Alexa is a virtual assistant released by Amazon. Using itself as a system for home automation, Alexa can...

4 minutes read.