mercredi 22 décembre 2021

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 :

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

Aucun commentaire:

Enregistrer un commentaire