Saturday 1 August 2020

Printing Pattern in Python (Triangle Pattern type-1)



Problem


You are given a positive integer . Print a numerical triangle of height  like the one below:
1
22
333
4444
55555
...........
How to think??
Observing the pattern carefully we can see that
  1. First row we have 1*1
  2. In second we Have 11*2
  3. Then 111*3
  4. and so on.
Now we make out we have to multiply the row number. But how to get the first part?
we observe that
  1. We can obtain 1 as quotient obtained when 10 is divided by 9
  2. Similarly we can obtain 11 as quotient when 100 is divided by 9.
Therefore we need powers of 10 at each row and divide them by 9 and multiply the quotient by row number and that's it.
How do we get power of 10??
 we have 2 options:
  1. Use power function invoked as pow() and use it as pow(10,i) where i is row number starting from 1.
  2. Writing 10**i simply where ** indicates power.
Now for N-1 rows we have to initiate a loop running N-1 times.
This can be done as:
for i in range(1,N):
Final Solution:
for i in range(1,int(input())):

    print(i*(pow(10,i)//9))

Sample Input

5

Sample Output

1
22
333
4444

𝑲𝒖𝒅𝒐𝒔 , 𝒚𝒐𝒖 𝒋𝒖𝒔𝒕 𝒔𝒐𝒍𝒗𝒆𝒅 𝒚𝒐𝒖𝒓 𝒇𝒊𝒓𝒔𝒕 𝒑𝒂𝒕𝒕𝒆𝒓𝒏 𝑷𝒓𝒐𝒈𝒓𝒂𝒎 𝒊𝒏 𝒑𝒚𝒕𝒉𝒐𝒏!!

Previous Post
Next Post