Monday 28 December 2020

Python Program to Print the Pascal’s triangle for n number of rows given by the user

 This is a Python Program to print the pascal’s triangle for n number of rows given by the user.

Problem Description

The program takes a number n and prints the pascal’s triangle having n number of rows.

Problem Solution

1. Take in the number of rows the triangle should have and store it in a separate variable.
2. Using a for loop which ranges from 0 to n-1, append the sub-lists into the list.
3. Then append 1 into the sub-lists.
4. Then use a for loop to determine the value of the number inside the triangle.
5. Print the Pascal’s triangle according to the format.
6. Exit.

Program/Source Code

Here is source code of the Python Program to print the pascal’s triangle for n number of rows given by the user. The program output is also shown below.

n=int(input("Enter number of rows: "))
a=[]
for i in range(n):
    a.append([])
    a[i].append(1)
    for j in range(1,i):
        a[i].append(a[i-1][j-1]+a[i-1][j])
    if(n!=0):
        a[i].append(1)
for i in range(n):
    print("   "*(n-i),end=" ",sep=" ")
    for j in range(0,i+1):
        print('{0:6}'.format(a[i][j]),end=" ",sep=" ")
    print()
Program Explanation

1. User must enter the number of rows that the Pascal’s triangle should have.
2. The for loop is used to append sub-lists into an empty list defined earlier.
3. Then 1 is appended into all the sub-lists.
4. The for loop is used to determine the value of the number inside the triangle which is the sum of the two numbers above it.
5. The other for loop is used to print the Pascal’s triangle according to the format.

Runtime Test Cases
Case 1:	
Enter number of rows: 3
               1 
            1      1 
         1      2      1 
 
Case 2:
Enter number of rows: 4
                  1 
               1      1 
            1      2      1 
         1      3      3      1

No comments:

Post a Comment