Skip to content
scipython.com

Q6.1.9Verifying a magic square

Verify that the magic square created in Example E6.2 satisfies the conditions that it contains the numbers 1 to \(N^2\) and that its rows, columns and main diagonals sum to \(N(N^2+1)/2\).

Show solution

For example,

In [x]: N = 5
In [x]: Nsq = N**2
In [x]: np.allclose(np.sort(magic_square.flatten()),
                    np.linspace(1, Nsq, Nsq).astype(int))
Out[x]: True

In [x]: Nsum = N * (N**2 + 1) // 2
In [x]: np.allclose(np.sum(magic_square, axis=0), Nsum)
Out[x]: True

In [x]: np.allclose(np.sum(magic_square, axis=1), Nsum)
Out[x]: True

In [x]: n.allclose(np.diag(magic_square), Nsum)
Out[x]: True

In [x]: n.allclose(np.diag(np.fliplr(magic_square)), Nsum)
Out[x]: True

np.fliplr flips the array in the left/right direction. An alternative way to get this "other" diagonal is with a.ravel()[N-1:-N+1:N-1].