← Back to challenges

Check Magic Square

PythonHardalgorithmsarraysdata_structuresloops

Instructions

A "magic square" is a square divided into smaller squares each containing a number, such that the numbers in each vertical, horizontal, and diagonal row add up to the same value.

3x3 Magic Square

Write a function that takes a 2D list, checks if it's a magic square and returns either True or False depending on the result.

Examples

is_magic_square([
  [8, 1, 6],
  [3, 5, 7],
  [4, 9, 2]
]) ➞ True

is_magic_square([
  [16,  3,  2, 13],
  [ 5, 10, 11,  8],
  [ 9,  6,  7, 12],
  [ 4, 15, 14,  1]
]) ➞ True

is_magic_square([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]) ➞ False

Notes

  • Check diagonals as well.
  • Test input will always be square.
python3
Loading editor…
to run
Walks through the solution with reasoning and edge cases.