
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find the nth row of Pascal's Triangle in Python
Suppose we have a number n, we have to find the nth (0-indexed) row of Pascal's triangle. As we know the Pascal's triangle can be created as follows −
- In the top row, there is an array of 1.
- Subsequent row is made by adding the number above and to the left with the number above and to the right.
So few rows are as follows −
So, if the input is like 4, then the output will be [1, 4, 6, 4, 1]
To solve this, we will follow these steps −
- if n is same as 0, then
- return [1]
- if n is same as 1, then
- return [1,1]
- ls:= a list with [1,1], temp:= a list with [1,1]
- for i in range 2 to n+1, do
- ls:= temp
- temp:= a list with one value = 1
- for i in range 0 to size of ls -1, do
- merge ls[i],ls[i+1] and insert at the end of temp
- insert 1 at the end of temp
- return temp
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, n): if n==0: return [1] if n==1: return [1,1] ls=[1,1] temp=[1,1] for i in range(2,n+1): ls=temp temp=[1] for i in range(len(ls)-1): temp.append(ls[i]+ls[i+1]) temp.append(1) return temp ob = Solution() print(ob.solve(4))
Input
4
Output
[1, 4, 6, 4, 1]
- Related Articles
- Finding the elements of nth row of Pascal's triangle in JavaScript
- Program to generate Pascal's triangle in Python
- Java program to print Pascal's triangle
- Java Program to Print Star Pascal's Triangle
- Pascal's Triangle in C++
- Python Program to Print the Pascal's triangle for n number of rows given by the user
- Pascal's Triangle II in C++
- Program to find Nth Fibonacci Number in Python
- Program to find nth Fibonacci term in Python
- Python program using map function to find row with maximum number of 1's
- Finding the sum of all numbers in the nth row of an increasing triangle using JavaScript
- Python program using the map function to find a row with the maximum number of 1's
- How to print integers in the form of Pascal triangle using C?
- Python Program to Find Nth Node in the Inorder Traversal of a Tree
- Python map function to find the row with the maximum number of 1’s

Advertisements