Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

irregular spaces making pattern abnormal

I have a pattern which i printed using below code

Code :

n=5

def pyramidupdown(n):
  cnt=0
  space=2
  lst= [str(row) for row in reversed(range(1,n+1))]
  for i in range(1,n+1):
    if i == 1:
      s=' '.join(lst)
      print(s)
    else:
      lst[cnt]=' '
      s=' '.join(lst)
      print(s)     
      cnt = cnt + 1

It prints the pattern below as output :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

5 4 3 2 1
  4 3 2 1
    3 2 1
      2 1
        1

But my issue is with spaces when the n value is defined 2 digit like 15
the pattern is not printed properly

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
  14 13 12 11 10 9 8 7 6 5 4 3 2 1
    13 12 11 10 9 8 7 6 5 4 3 2 1
      12 11 10 9 8 7 6 5 4 3 2 1
        11 10 9 8 7 6 5 4 3 2 1
          10 9 8 7 6 5 4 3 2 1
            9 8 7 6 5 4 3 2 1
              8 7 6 5 4 3 2 1
                7 6 5 4 3 2 1
                  6 5 4 3 2 1
                    5 4 3 2 1
                      4 3 2 1
                        3 2 1
                          2 1
                            1

Expected output :

 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
    14 13 12 11 10 9 8 7 6 5 4 3 2 1
       13 12 11 10 9 8 7 6 5 4 3 2 1
          12 11 10 9 8 7 6 5 4 3 2 1
             11 10 9 8 7 6 5 4 3 2 1
                10 9 8 7 6 5 4 3 2 1
                   9 8 7 6 5 4 3 2 1
                     8 7 6 5 4 3 2 1
                       7 6 5 4 3 2 1
                         6 5 4 3 2 1
                           5 4 3 2 1
                             4 3 2 1
                               3 2 1
                                 2 1
                                   1

what changes do i need to make in existing code to print properly the pattern

>Solution :

I would just do it like this:

def pyramidupdown(n):
    for i in range(n,0,-1):
        lst = []
        for j in range(n,0,-1):
            s = str(j)
            lst.append(s if j <= i else ' '*len(s))
        print(" ".join(lst))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading