# Lo Shu Magic Square (Python)

I wrote a python program to find if a matrix is a magic square or not. It works, but I can't help feeling like I may have overcomplicated the solution. I have seen other implementations that were a lot shorter, but I was wondering how efficient/inefficient my code is and how I could improve it and/or shorten it to achieve the result I am looking for.

def main():

matrix = [[4,9,2],
[3,5,7],
[8,1,6]]

result = loShu(matrix)

print(result)

def loShu(matrix):

i = 0
j = 0

for i in range(0, len(matrix)):
for j in range(0, len(matrix[j])):
if ((matrix[i][j] < 1) or (matrix[i][j] > 9)):
return ("This is not a Lo Shu Magic Square - one of the numbers is invalid")

row1 = matrix + matrix + matrix
row2 = matrix + matrix + matrix
row3 = matrix + matrix + matrix

ver1 = matrix + matrix + matrix
ver2 = matrix + matrix + matrix
ver3 = matrix + matrix + matrix

diag1 = matrix + matrix + matrix
diag2 = matrix + matrix + matrix

checkList = [row1,row2,row3,ver1,ver2,ver3,diag1,diag2]

temp = checkList

for x in range (0, len(checkList)):
if checkList[x] != temp:
return ("This is not a Lo Shu Magic Square")

return ("This is a Lo Shu Magic Square")

main()

• Seems wrong, as it claims that [[1,1,1], [1,1,1], [1,1,1]] is a Lo Shu Magic Square. Apr 17, 2021 at 17:45

A more robust solution could turn to numpy. Specifically, you can check row and column sums by doing m.sum() and m.sum(axis=1), and compute the sums of the diagonals via m.trace() or by sum(np.diag(m)) and sum(np.diag(np.fliplr(m)).