[Solved] Find all possible magic squares (3×3) python


I’ll leave finding out how to generate a magic square as an exercise. If you’re still having trouble with it, you can find other questions on StackOverflow about how to generate a magic square of a given size in Python.

Once you have your 3×3 magic square magic(3) (as a numpy ndarray), you can obtain all of the possible magic squares of that size by performing all of the possible rotations and reflections on it:

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

This produces a list containing the following 8 magic 3×3 matrices:

[[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]]

0

solved Find all possible magic squares (3×3) python