3

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?

5
  • I guess there are nothing appended to exist list Commented Apr 8, 2016 at 15:16
  • 1
    Python functions always return a value. Commented Apr 8, 2016 at 15:20
  • The boolean values are appended to the list. Commented Apr 8, 2016 at 15:21
  • 1
    if all(exist): -- this is returning False for some reason. Figure that out, and you will discover the reasons why your function returns None. Commented Apr 8, 2016 at 15:22
  • @beiller thanks! You are right. I am looking into it now. Commented Apr 8, 2016 at 16:05

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @qwr. I add "else return False" to each level of "If" statement. The function returns T/F now. Guess previously, function return "None" when the "If" statement doesn't meet since I didn't specify "else". Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.