Magic Square

🎯 Solve a magic square.

  • create a magic square with 3 * 3 fields.

  • fill the square with the numbers from 1-9

  • the sum of the numbers in each row, column and diagonal shall be 15

  • use each number only once

  • print the finished square

Hints

  • Write a function that calculates all sums

  • A brute-force approach is to try out all permutations*

  • See the itertools module

Extra Challenge

Fill a magic square with 4 * 4 fields with the numbers 1-16 (sum 34).

If you don’t want to try all the possibilities (9!), you can describe the magic square as a linear system of equations. The Python package PuLP allows you to express the necessary equations in a very compact way.

Translated with www.DeepL.com