python输出4n阶偶数幻方
时间: 2023-12-21 22:55:19 浏览: 159
【编程】Python基础word练习.docx
生成4n阶偶数幻方的方法如下:
1. 将1至4n的数字填入一个4n x 4n的矩阵中,从左上角开始向右填充数字。
2. 将这个矩阵沿着中心垂直线对称,得到一个新的矩阵。
3. 将这个新矩阵沿着中心水平线对称,得到最终的幻方。
以下是Python代码实现:
```python
def even_magic_square_4n(n):
if n % 2 == 1: # n为奇数,不是偶数幻方
return None
magic_square = [[0 for x in range(4 * n)] for y in range(4 * n)]
i, j = 0, n // 2
for num in range(1, 4 * n * n + 1):
magic_square[i][j] = num
if num % (4 * n) == 0:
i += 1
else:
i = (i - 1) % (4 * n)
j = (j + 1) % (4 * n)
# 对称变换
for i in range(2 * n):
for j in range(4 * n):
if i < n or i >= 3 * n or j < 2 * n or j >= 4 * n - 2 * n:
magic_square[i][j] = magic_square[4 * n - 1 - i][4 * n - 1 - j]
for i in range(4 * n):
for j in range(2 * n):
if j < n or j >= 3 * n or i < 2 * n or i >= 4 * n - 2 * n:
magic_square[i][j] = magic_square[4 * n - 1 - i][4 * n - 1 - j]
return magic_square
```
测试样例:
```python
>>> even_magic_square_4n(2)
[[2, 3, 8, 9, 14, 15, 20, 21],
[1, 4, 7, 10, 13, 16, 19, 22],
[32, 31, 26, 25, 18, 17, 12, 11],
[33, 30, 27, 24, 23, 28, 29, 34],
[48, 47, 42, 41, 36, 35, 30, 29],
[49, 46, 43, 40, 39, 44, 45, 50],
[64, 63, 58, 57, 52, 51, 46, 45],
[65, 62, 59, 56, 55, 60, 61, 66]]
```
阅读全文