Editor

Magic Square Check

#259 · Games and puzzles · Beginner · 45 XP · about 10 min

A magic square of size n is an n by n grid that holds each of the whole numbers from 1 to n * n exactly once, arranged so that every row, every column and both main diagonals add up to the same total. Write is_magic(grid) that returns True if grid (a list of n rows, each a list of n numbers) is a magic square and False otherwise.

Examples

is_magic([[2, 7, 6], [9, 5, 1], [4, 3, 8]])   # returns True
is_magic([[2, 7, 6], [9, 5, 1], [4, 8, 3]])   # returns False
is_magic([[5, 5, 5], [5, 5, 5], [5, 5, 5]])   # returns False
is_magic([[1]])                               # returns True

In the first grid every row, column and diagonal adds up to 15. The third grid has equal totals everywhere, but it does not hold the numbers 1 to 9.

Note

  • The grid is always square, with n from 1 to 100.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.