在python中打印螺旋列表的问题

时间:2018-09-13 17:59:51

标签: python-3.x list

我在制作螺旋清单时遇到问题。 程序应输出一个大小为n×n的表,并以顺时针方式从左上角以螺旋状填充从1到n * n的数字,如示例所示(此处n = 5)< / p>

enter image description here

当n为偶数时有效,而当n为奇数时无效

n = int(input())
arr = [[0 for i in range(n)] for j in range(n)]
stop = 0
start = 0
elem = 1
while elem <= n*n:
    stop += 1
    for j in range(start, n-stop):
        i = start
        arr[i][j] = elem
        elem += 1
    for i in range(start, n-stop):
        j = n-stop
        arr[i][j] = elem
        elem += 1
    for j in range(n-stop, start, -1):
        i = n-stop
        arr[i][j] = elem
        elem += 1
    for i in range(n-stop, start, -1):
        j = start
        arr[i][j] = elem
        elem += 1
    start += 1
for i in range(len(arr)):
    for j in range(len(arr)):
        print(arr[i][j], end=' ')
    print()

请帮助,这里哪里有问题?

1 个答案:

答案 0 :(得分:0)

您可以使用numpy

import numpy as np

def spiral(n=5):
        a = np.arange(n*n)
        b = a.reshape((n,n))
        m = None
        for i in range(n, 0, -2):
            m = np.r_[m, b[0, :], b[1:, -1], b[-1, :-1][::-1], b[1:-1, 0][::-1]]
            b = b[1:-1, 1:-1]
        a[list(m[1:])]=list(a)  
        return a.reshape((n,n)) + 1
spiral()
array([[ 1,  2,  3,  4,  5],
       [16, 17, 18, 19,  6],
       [15, 24, 25, 20,  7],
       [14, 23, 22, 21,  8],
       [13, 12, 11, 10,  9]])
spiral(10)
array([[  1,   2,   3,   4,   5,   6,   7,   8,   9,  10],
       [ 36,  37,  38,  39,  40,  41,  42,  43,  44,  11],
       [ 35,  64,  65,  66,  67,  68,  69,  70,  45,  12],
       [ 34,  63,  84,  85,  86,  87,  88,  71,  46,  13],
       [ 33,  62,  83,  96,  97,  98,  89,  72,  47,  14],
       [ 32,  61,  82,  95, 100,  99,  90,  73,  48,  15],
       [ 31,  60,  81,  94,  93,  92,  91,  74,  49,  16],
       [ 30,  59,  80,  79,  78,  77,  76,  75,  50,  17],
       [ 29,  58,  57,  56,  55,  54,  53,  52,  51,  18],
       [ 28,  27,  26,  25,  24,  23,  22,  21,  20,  19]])