×

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 exit commands

exit(), quit(), sys.exit(), os._exit() In this tutorial, we will study exit commands used in the Python programming language. Python is undoubtedly the choice of programmer and this is because of the in-built...

3 minutes read.

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively. Typically, the body of a...

3 minutes read.

Compound Interest GUI Calculator using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Problem-solving with algorithm and data structures using Python

What is problem-solving? There is no universal method for solving problems. It's frequently a special process that balances your immediate and long-term goals with your available resources. However, several models emphasise...

3 minutes read.

Python Variables

Variables are one of the most important terms we should be familiar with if we want to be good programmers. In simpler words, we use variables to store a value....

4 minutes read.

How to clear screen in Python?

How to clear screen in python There are times when we execute our program and it results in an unexpected output. The obtained result can contain some kind of garbage values...

4 minutes read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

How to slice a list in python

When working with lists, we face situations where we may need a part of the list from one index to the other. Slicing is one of the simpler ways to...

5 minutes read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.

Python maketrans() function

Introduction A static method is the string maketrans() one. It is used to make a one-to-one mapping between a string's character and its translation, i.e., to define the list of characters...

5 minutes read.

Python str() function

Python str() function The str() function in Python converts the specified value into a string. Syntax class str(object='')           or class str(object=b'', encoding='utf-8', errors='strict') Parameter object:  This parameter represents any object to convert the given...

1 minute read.

Python Project Ideas

One of the most widely used programming languages today is Python. This pattern appears set to continue through 2023 and beyond. Therefore, working on some current Python project ideas is the...

10 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Permutations in Python

Recursion Basic idea: for numbers of length N. N-1 items are chosen at random between 0 and then generate permutations using the remaining N-1 elements in a recursive fashion. Once you've done...

4 minutes read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Python Simple Interest

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Check Palindrome in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Allocate a minimum number of pages in python

You have given a sorted array of size n which represents the number of pages in n different books and an integer value which denotes the number of students. We...

4 minutes read.