Pascal’s Triangle using Python

Pascal’s Triangle is one of the popular coding interview questions. It is asked in the coding interviews by FAANG companies many times. In Pascal’s Triangle problem, we need to return the number of rows of a Pascal’s Triangle. So, if you want to learn how to solve Pascal’s Triangle problem, this article is for you. In this article, I will take you through how to solve Pascal’s Triangle problem using Python.

Pascal’s Triangle using Python

In the rows of a Pascal’s Triangle, each number is the sum of two numbers directly above it. The image below shows the structure of Pascal’s Triangle.

Pascal's Triangle

In this problem, you will get the number of rows as an input, and you need to output the rows of Pascal’s Triangle by following the structure of Pascal’s Triangle. For example, have a look at the input and output below to get an idea about how to solve this problem in a coding interview:

Input: num of rows = 5
Output: [[1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]

I hope you now have understood what Pascal’s Triangle is. Below is how to solve the Pascal’s Triangle problem using the Python programming language:

def generate(numRows):
    triangle = [[1]]
    row = 0
    while numRows > len(triangle):
        row = row + 1
        triangle.append([1] * (row + 1))
        for i in range(1, row):
            triangle[row][i] = triangle[row - 1][i - 1] + triangle[row -1][i]
    return triangle

print(generate(5))
Output: [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]

So this is how you can solve Pascal’s triangle problem using Python. You can find many more practice questions to improve your problem-solving skills using Python here.

Summary

In the Pascal’s Triangle problem, you will get the number of rows as an input, and you need to output the rows of Pascal’s Triangle by following the structure of Pascal’s Triangle. I hope you liked this article on how to solve Pascal’s Triangle problem. Feel free to ask valuable questions in the comments section below.

Default image
Aman Kharwal

Coder with the ♥️ of a Writer || Data Scientist | Solopreneur | Founder

Articles: 1297

Leave a Reply