Reputation: 459
I am trying to write a Python function which can return "True" or "False" in evaluating a magic square. A magic square is a matrix all of whose row sums, column sums and the sums of the two diagonals are the same. (One diagonal of a matrix goes from the top left to the bottom right, the other diagonal goes from top right to bottom left.)
Here is my code:
def isMagic(A3):
dim = A3.shape[0] * A3.shape[1]
construct = np.arange(1,dim+1)
if A3.shape[0] == A3.shape[1]:
exist = []
for r in range(len(A3)):
for c in range(len(A3)):
exist.append(A3[r,c] in construct)
if all(exist):
def all_same(items):
return all(x == items[0] for x in items)
dig_1 = sum(np.diag(A3))
dig_2 = sum(np.diag(np.fliplr(A3)))
dig = all_same(np.array([dig_1, dig_2]))
column = all_same(np.sum(A3, axis = 1))
row = all_same(np.sum(A3, axis = 0).transpose())
if all(dig, column, row):
return True
else:
return False
Yet, when I try to test my code on one of the magic square, the function doesn't return any value:
test2 = np.matrix([[8, 1, 6],
[3, 5, 7],
[4, 9, 2]])
isMagic(test2) # True
I wondered that if it was because the indentation?
Upvotes: 3
Views: 1052
Reputation: 10891
For your first two if
statements if A3.shape[0] == A3.shape[1]
and if all(exist)
, notice if the condition is false, nothing (None
) is returned. I guess you want to return False if all of your if conditions are not met. Then just put return False
at the very end of the function so it is run if return True
is not reached:
def isMagic(A3):
...
return False
Upvotes: 4