Python打出"旋涡"矩阵

实现一个函数,输入正整数n,打印出如下矩阵(n*n, n=4):
[10,11,12, 1 ]
[ 9 ,16,13, 2 ]
[ 8 ,15,14, 3 ]
[ 7 , 6 , 5 , 4 ]

import numpy as np
def whirlpool_matrix(n=9):
    mat = np.array([[0]*n]*n)
    value = 0
    i, j = -1, n - 1
    for offset in range(n, 0, -1):
        value += 1
        i += 1
        mat[i][j] = value
    for m in range(n - 1, 0, -1):
        for offset in range(m, 0, -1):
            value += 1
            j += (-1) ** (m + n)
            mat[i][j] = value
        for offset in range(m, 0, -1):
            value += 1
            i += (-1) ** (m + n)
            mat[i][j] = value
    return mat

matrix = whirlpool_matrix()
print(matrix)

另外可使用matplotlib进行可视化,下面输出热力图

import seaborn
import matplotlib.pyplot as mpt
seaborn.heatmap(matrix, center=81, annot=True)  # center设置中心颜色
mpt.show()

旋涡矩阵

猜你喜欢

转载自blog.csdn.net/yellow_python/article/details/80523897