0

所以我需要制作一个数字网格,这是一个权力网格。所以用户输入 2 个数字,然后网格使用索引并制作一个网格。如果用户输入 5 和 5 它将显示

1 1 1 1 1
2 4 8 16 32
3 9 27 81 243
4 16 64 256 1024
5 25 125 625 3125

但它需要右对齐,以便在“单位列”中显示单位。间隙基于表示最高数字的字符串的长度(32 是 2 个字符长) 基本上,完全取决于用户输入的内容,但间隙必须减小,因为数字变长了。希望这是有道理的。

4

3 回答 3

1

这很好用(希望这相当优雅并且不太难理解):

import math

def print_grid(x, y):
    # Get width of each number in the bottom row (having max values).
    # This width will be the column width for each row.
    # As we use decimals it is (log10 of the value) + 1.
    sizes = [int(math.log10(math.pow(y, xi)) + 1) for xi in range(1, x + 1)]
    for yj in range(1, y + 1):
        row = ''
        for xi in range(1, x + 1):
            value = pow(yj, xi)
            template = '%{size}d '.format(size=sizes[xi-1])
            row += template % value
        print row

print_grid(5, 5)

使用所需的输出:

1  1   1   1    1 
2  4   8  16   32 
3  9  27  81  243 
4 16  64 256 1024 
5 25 125 625 3125
于 2013-10-28T17:38:51.520 回答
1
def pow_printer(max_val, max_pow):
    # What we are doing is creating sublists, so that for each sublist, we can
    # print them separately
    _ret = [[pow(v, p) for p in range(1, max_pow+1)] for v in range(1, max_val+1)]
    # The above produces, with max_val = 5 and max_pow = 5:
    # [[1, 1, 1, 1, 1], [2, 4, 8, 16, 32], [3, 9, 27, 81, 243], [4, 16, 64, 256, 1024], [5, 25, 125, 625, 3125]]

    # Now, we are looping through the sub-lists in the _ret list
    for l in _ret:
        for var in l:
            # This is for formatting. We as saying that all variables will be printed
            # in a 6 space area, and the variables themselves will be aligned
            # to the right (>)
            print "{0:>{1}}".format(var,
                                    len(str(max_val**max_pow))),  # We put a comma here, to prevent the addition of a
            # new line
        print  # Added here to add a new line after every sublist

# Actual execution
pow_printer(8, 7)

输出:

  1       1       1       1       1       1       1
  2       4       8      16      32      64     128
  3       9      27      81     243     729    2187
  4      16      64     256    1024    4096   16384
  5      25     125     625    3125   15625   78125
  6      36     216    1296    7776   46656  279936
  7      49     343    2401   16807  117649  823543
  8      64     512    4096   32768  262144 2097152

工作示例。

于 2013-10-28T16:57:40.037 回答
0

假设您已经获得了所需的数字,请查看http://code.google.com/p/prettytable/

# Set up the number lists already
zz
[[1, 1, 1, 1, 1],
 [2, 4, 8, 16, 32],
 [3, 9, 27, 81, 243],
 [4, 16, 64, 256, 1024],
 [5, 25, 125, 625, 3125]]

p = prettytable.PrettyTable()
for z in zz:
    p.add_row(z)

# Optional styles
p.align='r'
p.border=False
p.header=False

print p
 1   1    1    1     1
 2   4    8   16    32
 3   9   27   81   243
 4  16   64  256  1024
 5  25  125  625  3125

ps = p.get_string()
于 2013-10-28T18:10:03.740 回答