找到所有可能的幻方 (3x3) python

Find all possible magic squares (3x3) python

我需要这些人上学,请帮忙。 我只能找到一个幻方,请问如何找到。

我将找出如何生成幻方作为练习。如果您仍然遇到问题,您可以在 Python.

中找到关于如何生成给定大小的幻方的其他问题。

一旦你有了 3x3 幻方 magic(3)(作为 numpy ndarray),你可以通过对其执行所有可能的旋转和反射来获得该大小的所有可能的幻方:

rotations = [np.rot90(magic(3), x) for x in range(4)]
reflections = [np.flip(x, 1) for x in rotations]
all_magic_3x3 = rotations + reflections

这会生成一个包含以下 8 个 3x3 魔法矩阵的列表:

[[8 1 6]
 [3 5 7]
 [4 9 2]]

[[6 7 2]
 [1 5 9]
 [8 3 4]]

[[2 9 4]
 [7 5 3]
 [6 1 8]]

[[4 3 8]
 [9 5 1]
 [2 7 6]]

[[6 1 8]
 [7 5 3]
 [2 9 4]]

[[2 7 6]
 [9 5 1]
 [4 3 8]]

[[4 9 2]
 [3 5 7]
 [8 1 6]]

[[8 3 4]
 [1 5 9]
 [6 7 2]]
from itertools import permutations

def generate_all_magic_squares():
    magic_squares = []
    for seq in permutations(range(1, 10)):
        cand = [seq[i:i+3] for i in range(0, 9, 3)]
        # filter cand whose row sum is a const
        if sum(cand[0]) == sum(cand[1]) == sum(cand[2]):
            cols = list(zip(*cand)) # invert cols to rows to check their sums as well
            if sum(cols[0]) == sum(cols[1]) == sum(cols[2]) == sum(cand[0]):
                pd =  [cand[0][0],cand[1][1],cand[2][2]] # principle diagnol
                od =  [cand[0][2], cand[1][1], cand[2][0]] # other diagnol
                if sum(pd) == sum(od) == sum(cand[0]): # check the sums of the diagnol are equal to other rows/cols
                    magic_squares.append(cand)

    return magic_squares