我正在尝试制作一个看起来像这样的螺旋
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
这是我的代码,它打印出一个矩阵,但数字从外部开始,其中的工作与我想要的相反。我怎么能改变这个?
def main():
spiral = open('spiral.txt', 'r') # open input text file
dim = int(spiral.readline()) # read first line of text
num = int(spiral.readline()) # read second line
spiral.close()
print(dim)
if dim % 2 == 0: # check to see if even
dim += 1 # make odd
print(dim)
print(num)
dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
x, y, c = 0, -1, 1
m = [[0 for i in range(dim)] for j in range(dim)]
for i in range(dim + dim - 1):
for j in range((dim + dim - i) // 2):
x += dx[i % 4]
y += dy[i % 4]
m[x][y] = c
c += 1
print(m)
print('\n'.join([' '.join([str(v) for v in r]) for r in m]))
print(num)
main()
答案 0 :(得分:1)
替换
m[x][y] = c
通过
m[x][y] = dim**2 + 1 - c
基本上倒数了。您也可能希望与:
保持适当的间距print('\n'.join([' '.join(["{:2}".format(v) for v in r[::-1]]) for r in m]))