*If you want to build a magic square, check this article, the python code is at the bottom – How to build a magic square*

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:

1 2 3 4 5 |
print(magic_square([[1,2,3], [4,5,6], [7,8,9]])) print(magic_square([[4,9,2], [3,5,7], [8,1,6]])) print(magic_square([[7,12,1,14], [2,13,8,11], [16,3,10,5], [9,6,15,4]])) print(magic_square([[23, 28, 21], [22, 24, 26], [27, 20, 25]])) print(magic_square([[16, 23, 17], [78, 32, 21], [17, 16, 15]])) |

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:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] [12, 15, 18, 6, 15, 24, 15, 15] False [[4, 9, 2], [3, 5, 7], [8, 1, 6]] [15, 15, 15, 15, 15, 15, 15, 15] True [[7, 12, 1, 14], [2, 13, 8, 11], [16, 3, 10, 5], [9, 6, 15, 4]] [34, 34, 34, 34, 34, 34, 34, 34, 34, 34] True [[23, 28, 21], [22, 24, 26], [27, 20, 25]] [72, 72, 72, 72, 72, 72, 72, 72] True [[16, 23, 17], [78, 32, 21], [17, 16, 15]] [111, 71, 53, 56, 131, 48, 63, 63] False |

At the end, here comes the code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
def magic_square(matrix): iSize = len(matrix[0]) sum_list = [] #Vertical: for col in range(iSize): sum_list.append(sum(row[col] for row in matrix)) #Horizontal sum_list.extend([sum (lines) for lines in matrix]) #Diagonals dlResult = 0 for i in range(0,iSize): dlResult +=matrix[i][i] sum_list.append(dlResult) drResult = 0 for i in range(iSize-1,-1,-1): drResult +=matrix[i][i] sum_list.append(drResult) if len(set(sum_list))>1: return False return True |

Yup! That’s it! 🙂