0
How can I write a function to test whether a matrix magic square
2 Answers
+ 2
"""
Ok, fine, I think I got it. I wrote a function which iterates through rows, columns and diagonals, sequentially. The code can be four times simpler by using four temporary sums instead of one, but I leave it for educational purpose to see what it is doing.
Also, I left matrix2 from the previous attempt to show false result, too.
"""
matrix = [[2, 7, 6], [9, 5, 1], [4, 3, 8]]
matrix2 = [[4, 5, 7], [3, 6, 8], [7, 8, 9]]
def is_magic(square):
magic_sum = 0
check_sum = 0
for x in range(len(square)):
check_sum += square[0][x]
print(check_sum)
# check for the sum of the first row as a control sum
for y in range(len(square)):
for x in range(len(square)):
magic_sum += square[x][y]
if magic_sum != check_sum:
print(magic_sum)
return False
else:
print(magic_sum)
magic_sum = 0
#rows checked
for y in range(len(square)):
for x in range(len(square)):
magic_sum += square[y][x]
if magic_sum != check_sum:
print(magic_sum)
return False
else:
print(magic_sum)
magic_sum = 0
# columns checked
for x in range(len(square)):
magic_sum += square[x][x]
if magic_sum != check_sum:
print(magic_sum)
return False
else:
print(magic_sum)
magic_sum = 0
# diagonal checked
for x in range(len(square)):
magic_sum += square[len(square)-x-1][x]
if magic_sum != check_sum:
print(magic_sum)
return False
else:
print(magic_sum)
magic_sum = 0
# contrdiagonal checked
return True
# if got here, everything is checked positive
print(is_magic(matrix))
print(is_magic(matrix2))
0
Thank you so much