Magic Square

Created by Julien Palard

Implement the fill_magic_square function.

It takes a single argument: a numpy.array of integers representing a partially filled magic square. Holes are represented using zeros.

Your fill_magic_square function will have to find and fill the gaps in the square.

Do not return a value, just modify the square in-place.

Beware, my magic squares may contain any natural number (> 0), I do not restrict myself to magic squares with numbers from 1 to square_size ** 2.

Examples

import numpy as np
easy_square = np.array([
    [2, 7, 6],
    [9, 0, 1],
    [4, 3, 8],
])
fill_magic_square(easy_square)
print(easy_square)

Should give:

array([[ 2, 7, 6 ],
       [ 9, 5, 1 ],
       [ 4, 3, 8 ]]])

An harder one:

import numpy as np
harder_square = np.array([
     [ 4,  0, 15,  0],
     [ 9,  0,  6, 12],
     [ 5, 11, 10,  0],
     [16,  0,  0, 13],
])
fill_magic_square(harder_square)
print(harder_square)

Should give:

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

Notice how this can always be solved without doing advanced math as there's always an obvious move to do. So there's always a single valid solution. I'll never give you np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]), I promise.

There's no corrections yet, hit the `Submit` button to send your code to the correction bot.

Keyboard shortcuts:

  • Ctrl-Enter: Send your code to the correction bot.
  • Escape: Get back to the instructions tab.

See solutions