Python – Calculate magic square with python

A magic square is an arrangement of the numbers from 1 to N^2 (N-squared) in an NxN matrix, with each number occurring exactly once, and such that the sum of the entries of any row, any column, or any main diagonal is the same. Something like this:

The task of the python code is to get a square with any dimensions and to determine whether it is a magic square or not. This is a possible input:

How is the result determined?


In my case, I generate a list and I add to it the sum of all the vertical and horizontal lines. Then I add the two diagonals. At the end, I check whether all the values in the list are the same. If they are the same, this means that the square is a magic one. These are the values of the lists and the results:

At the end, here comes the code:

Yup! That’s it! 🙂

Tagged with: , , , ,