python - 以菱形打印数字

标签 python

我遇到了这个问题:http://codegolf.com/numeric-diamonds这要求您以这种格式打印数字:

  1
 4 2
7 5 3
 8 6
  9
           1
         7   2
      13   8   3
    19  14   9   4
  25  20  15  10   5
31  26  21  16  11   6
  32  27  22  17  12
    33  28  23  18
      34  29  24
        35  30
          36
                             1
                         11     2
                      21    12     3
                   31    22    13     4
                41    32    23    14     5
             51    42    33    24    15     6
          61    52    43    34    25    16     7
       71    62    53    44    35    26    17     8
    81    72    63    54    45    36    27    18     9
 91    82    73    64    55    46    37    28    19    10
    92    83    74    65    56    47    38    29    20
       93    84    75    66    57    48    39    30
          94    85    76    67    58    49    40
             95    86    77    68    59    50
                96    87    78    69    60
                   97    88    79    70
                      98    89    80
                         99    90
                           100

我能够很好地找到进入特定行的数字,但我排列它们的逻辑相当模糊。

for i in range(2*n - 1):
    m = <list of numbers for this row>
    row_width = (n+i)*(n/3) if i < n else row_width - (n/3)

    print ''.join(str(i).rjust(n/2 + 1) for i in m).strip().rjust(row_width))

从代码高尔夫的角度来看这是可以的,但是有没有一种干净的、Pythonic 的方法来以这种格式排列 2D 数组中的数字?

最佳答案

不知道“pythonic”,但这对我来说看起来很干净:

size = 10
maxlen = len(str(size * size))
m = size * 2 - 1
matrix = [[' ' * maxlen] * m for _ in range(m)]

for n in range(size * size):
    r = n // size
    c = n % size
    matrix[c + r][size - r - 1 + c] = '{0:{1}}'.format(n + 1, maxlen)

print '\n'.join(''.join(row) for row in matrix)

关于python - 以菱形打印数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22049202/

相关文章:

python - 在 python 中是否有与 string.format() 相反的设置/从字符串中提取值

python mysql 获取查询

Python 处理 Web 表单

python - 在 python 中使用 networkx 计算无向图中大小为 k 的集团的最佳方法是什么?

python - 用字典替换字符串中的多个单词(python)

python - 如何将 Pygame 程序编译为 Windows .exe

python - Tkinter 列表框

python - 如何在 python 中正确执行 host 或 dig 命令

未呈现的 Python 页面

python - 将字符串转换为 int python