2013-10-28 4 views
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 자입니다). 기본적으로 사용자가 입력 한 내용에 따라 다르지만 길어지기 때문에 간격이 줄어들 수 있습니다. 희망이 의미가 있습니다.

+0

참조 : http://docs.python.org/2/library/string.html#format-specification-mini -언어 – BlackVegetable

답변

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) 

출력 : 원하는 출력으로

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  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 

Working example.

1

(이 이해하기 너무 어려운 오히려 우아하고 있지 희망) :

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 
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() 
관련 문제