Search This Blog

Saturday, 4 July 2020

Print mirror number pattern in python

Mirror Number Pattern

Problem Description: You are given with an input number N, then you have to print the given
pattern corresponding to that number N.
For example if N=4
Pattern output : 1
 12
 123
 1234

How to approach?
1. Take N as input from the user.
2. Figure out the number of rows, (which is N here) and run a loop for that.
3. Now, figure out how many columns are there in ith row and run a loop for that within
this. Here, first you need to run a loop to print the spaces too.
4. Now, figure out “What to print?” in a particular (row, column). It can depend on the
column number, row number or N.
Pseudo code for the given problem:
input=N
i=1
While i is less than or equal to N:
 spaces=1
 While spaces is less than (n-i):
 print(‘ ‘)
 Increment spaces by 1
 j=1
 While j is less than or equal to i:
 print(j)
 Increment j by 1
 Increment i by 1
 Add a new line here
❏ Let us dry run the Code for N=4
● i=1(<=4)
➔ 4-1=3 spaces are getting printed first.
➔ j=1(<=1), so print=1+1-1=1
➔ j=2 (>1), move out of the inner loop with a new line
● i=2(<=4)
➔ 4-2=2 spaces are getting printed first.
➔ j=1 (<=2), so print 1
➔ j=2 (<=2) , so print 2
➔ j=3(>2), move out of the inner loop with a new line
● i=3(<=4)
➔ 4-3=1 space is getting printed first.
➔ j=1(<=3), so print 1
➔ j=2(<=3), so print 2
➔ j=3(<=3), so print 3
➔ j=4(>3), move out of the inner loop with a new line
● i=4(<=4)
➔ 4-4=0 no space is getting printed.
➔ j=1(<=4), so print 1
➔ j=2(<=4), so print 2
➔ j=3(<=4), so print 3
➔ j=4(<=4), so print 4
➔ j=5(>4), move out of the inner loop with a new line
● i=5(>4), move out of the loop
So , final output:
 1
 12
 123
 1234

HINT

Code : Mirror Number Pattern

Print the following pattern for the given N number of rows.
Pattern for N = 4



  • The dots represent spaces.

Input format :
Integer N (Total no. of rows)

Output format :
Pattern in N lines

Constraints
0 <= N <= 50

Sample Input 1:
3

CODE:

## Read input as specified in the question
## Print the required output in given format
n = int(input())
i = 1
while i <= n:
    spaces = 1
    while spaces <= n-i:
        print(" ", end = '')
        spaces = spaces + 1
    num= 1
    while num<=i:
        print(num, end='') 
        num= num+1   
    print()
    i = i + 1

Sample Output 1:
      1
    12
  123

Console based:




No comments:

Post a Comment