jeudi 23 décembre 2021

How to print following pattern getting issue with spaces?

I am trying to write the code but not getting how to achieve expected output Causing issue with space and not able to make proper judgement how to get exact spaces after every iteration

My code :

n=15
cnt=0
lst=[str(' ') for x in range(1,n+1)]
initial_length=len(''.join(lst))
print(initial_length)
for row in range(1,n+1):
  lst[cnt-1]=str(row)
  cnt=cnt-1
  print(' '.join(lst))

Output of above code is not as expected output

                            1
                          2 1
                        3 2 1
                      4 3 2 1
                    5 4 3 2 1
                  6 5 4 3 2 1
                7 6 5 4 3 2 1
              8 7 6 5 4 3 2 1
            9 8 7 6 5 4 3 2 1
          10 9 8 7 6 5 4 3 2 1
        11 10 9 8 7 6 5 4 3 2 1
      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
  14 13 12 11 10 9 8 7 6 5 4 3 2 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

Expected output :

                                  1
                                2 1                                                                 
                              3 2 1                                                              
                            4 3 2 1
                          5 4 3 2 1                         
                        6 5 4 3 2 1                       
                      7 6 5 4 3 2 1                     
                    8 7 6 5 4 3 2 1 
                  9 8 7 6 5 4 3 2 1
               10 9 8 7 6 5 4 3 2 1 
            11 10 9 8 7 6 5 4 3 2 1 
         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
   14 13 12 11 10 9 8 7 6 5 4 3 2 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

Aucun commentaire:

Enregistrer un commentaire