Kth Row of Pascal’s Triangle using Python

In this lesson, we will learn and solve how to print the Kth Row of Pascal’s triangle in Python using simple operations.

Start with the definition of Pascal’s Triangle.

Pascal Triangle is a triangular array/list (2D) which is made by summing the adjacent element/number from the previous row.

Below is Pascal’s Triangle for 7 rows.


Print Kth Row of Pascal’s Triangle

So in simple words, Pascal’s Triangle is :

To generate t[i] in row R ,then sum up t'[i] and t'[i-1] from previous row R-1.

NOTE: Here K = 1 means row 0(zero) i.e. t[0] .

1. Example:

INPUT: K = 1


2. Example:

INPUT: K = 4

OUTPUT: [1,4,6,4,1]

Now start with the implementation of a function to print the Kth row. This question is directly asked by GOOGLE in Coding/Interview rounds.

Code for printing/returning the Kth Row of Pascal’s Triangle in Python using simple operations.

def KROW(K):                            #defining function with argument.
    LIST = []                           # list declare.
    if(K == 1):
        return(LIST[-1])                # return [1] if K = 1.
    if(K == 2):
        return(LIST[-1])                # return [1,1] if K = 2.
    while(len(LIST)!=K):                # iterate till pascal's triangle not form till K rows.
        l = []
        l.append(1)                     # every row starts with 1.
        for i in range(0,len(LIST[-1])-1):
            a = LIST[-1][i]+LIST[-1][i+1]   # sum up two numbers from previous row for the current row's element .
        l.append(1)                         # last element of each row will be 1.
        LIST.append(l)                      # forming each row and storing in 2-D LIST.
    return(LIST[-1])                        # returning Kth row.

If passing the K value as an argument in the defined function KROW we will get Kth Row as corresponding as mentioned in the problem statement.



[1, 1]
[1, 2, 1]
[1, 3, 3, 1]

Comment your suggestion for this tutorial if required. Do comment if you like or you can also give your suggestion to improve this. Try to solve this question on coding sites on your own will help you more after learning from here.

Leave a Reply

Your email address will not be published. Required fields are marked *