Magic Square Identification in Python
In this tutorial, we are going to learn how to identify whether a given matrix is a magic square or not in Python. First, let’s take a look at what we mean by a magic square in terms of matrices.
What is a Magic Square?
A Magic Square is a square matrix in which the sum of all its rows, all its columns, and all its diagonals is equal to a single number and this number is called the Magic Constant or Magic Number.
Let’s take a look at an example:
0,2,4,6
6,6,0,0
1,1,5,5
5,3,3,1
This is a magic square with magic constant = 12
How to identify whether a given matrix is a Magic Square or not in Python?
For identifying a magic square, we need to keep in our minds that the sum of every row, every column, and every diagonal must be equal to each other. This is a simple enough task. So, here’s how we proceed:
- Take the sum of the first row as the magic constant.
- Check all other sums of rows, columns, and diagonals.
- If any row/column/diagonal found whose sum is not equal to the magic constant → return False
- Else return True
In order to make our task simpler and our code more interpretable, we will decompose our task into the following tasks:
- rows- all the rows of the square matrix do not add up to the magic number returns False
- columns- all the rows of the square matrix do not add up to the magic number returns False
- diagonals- all the rows of the square matrix do not add up to the magic number returns False
Implementing the code in Python
Below is our code:
def rows(square, magic_num): n = len(square) for i in range(n): sum_row = 0 for j in range(n): sum_row += square[i][j] if sum_row != magic_num: return False return True def columns(square, magic_num): n = len(square) for i in range(n): sum_col = 0 for j in range(n): sum_col += square[j][i] if sum_col != magic_num: return False return True def diagonals(square, magic_num): n = len(square) #left_to_right sum_diag = 0 for i in range(n): sum_diag += square[i][i] if sum_diag != magic_num: return False #right to left sum_diag = 0 for i in range(n): sum_diag += square[i][-(i+1)] return sum_diag == magic_num # this is our main function def magic_square(square): # find magic number magic_constant = 0 for n in square[0]: magic_constant += n return ( rows(square, magic_constant) and columns(square, magic_constant) and diagonals(square, magic_constant) )
Let’s run the above-mentioned example:
sq = [[0,2,4,6], [6,6,0,0], [1,1,5,5], [5,3,3,1]] magic_square(sq)
Output:
True
Thank you for sparing your valuable time to read this article. You may check out other articles as well:
- Construct a String from another String using Suffix Trie in Python
- Implementing Quick Select in Python
Leave a Reply