不规则空间使图案异常

irregular spaces making pattern abnormal

我有一个图案,是用下面的代码打印的

代码:

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

它打印下面的模式作为输出:

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

但我的问题是当 n 值定义为 2 位数字时,如 15 图案打印不正确

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

预期输出:

 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

我需要对现有代码进行哪些更改才能正确打印图案

我会这样做:

def pyramidupdown(n):
    for i in range(n,0,-1):  # loop n rows (in descending order)
        lst = []
        for j in range(n,0,-1): # loop n numbers (in descending order)
            s = str(j)
            # at the i-th row replace the first i string numbers
            # (i.e. where j > i)
            # by as many spaces as there are characters in that string  
            if j <= i:
                lst.append(s)
            else:
                lst.append(' '*len(s)) 
        print(" ".join(lst))

你甚至可以把它变成 1-liner(只是为了好玩):

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

既然我理解了您的代码:这里是使其工作的最小调整:

def pyramidupdown(n):
  cnt=0
  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]=' '*len(lst[cnt]) # here replace by correct number of spaces
      s=' '.join(lst)
      print(s)     
      cnt = cnt + 1