I already wrote one part of the program which is below:
def matrix_is_square(matrix):
for i in range(len(matrix)):
if len(matrix[i]) != len(matrix):
return False
return True
This function returns True if matrix is a square matrix, otherwise, it returns False.
HOWEVER, HERE'S WHEN THE PROBLEM BEGINS.
I Have to write a second function that determines if the function is Magic square.
A square matrix forms a magic square if the following conditions are met:
- The elements of the matrix are numbers 1,2,3,...,n2
- The sum of the elements in each row, in each column and in the two diagonals is the same value
The code first begins with:
def magic(matrix):
if(not(is_square(matrix))):
return False
# The remaining code
This is what I attempted.
square = []
for i in range(len(matrix)):
square.append([])
for j in range(len(matrix)):
square[i].append(0)
total = 0
x = len(matrix)
for i in range(x):
total += square[i][i]
if total != x*(x*x+1)/2:
return False
else:
return True
total = 0;
for i in range(x):
total += square[i][x-1-i]
if total != x*(x*x+1)/2:
return False
else:
return True
There seem to be a couple of errors in my code. An important one is that I'm testing for exact equality of numbers, which is wrong because numbers cannot be represented exactly as floating points, but I can't find another way to do that. Any hints would be appreciated.
Here are the expected outcomes of this function just to be on the same page.
True
[[2,7, 6],[9,5,1],[4,3,8]]
[[16,3,2,13], [5,10,11,8],[9,6,7,12], [4,15,14,1]]
False
[[1,2,3,4], [5,6,7,8],[9,10,11,12], [13,14,15,16]]
[[1,1],[1,1]]
[[1,1],[1,1],[1,2]]
No import numpy.