i'm trying to make a function that checks whether or not a matrix is a magic square. i only need to check the vertical and horizontal (not diagonal). sometimes it passes and sometimes it fails. i was hoping that someone could help me solve the issue. this is my code:
for i in range(len(m)):
if len(m[i]) != len(m):
return False
return True
and this is the one that fails. it returns false:
m = [ [1,2,3,4]
, [5,6,7,8]
, [9,10,11,12]
, [13,14,15,16]
]
print(magic_square(m)) == False)
The code you provide does not check if a matrix is a magic square, it only checks if a matrix (in this case, a list of lists) is square. After this check, you need to calculate the sums of each row, each column and each diagonal (although for some reason you said you don't need those) and compare if all of them are equal.
If you are ok with using numpy then you can use
m = np.array(m)
len(np.unique(np.concatenate([m.sum(axis=1), m.sum(axis=0)]))) == 1
Test cases:
m = [ [1,2,3,4]
, [5,6,7,8]
, [9,10,11,12]
, [13,14,15,16]
]
m = np.array(m)
print (len(np.unique(np.concatenate([m.sum(axis=1), m.sum(axis=0)]))) == 1)
m = [ [2,7,6]
, [9,5,1]
, [4,3,8]
]
m = np.array(m)
print (len(np.unique(np.concatenate([m.sum(axis=1), m.sum(axis=0)]))) == 1)
Output:
False
True
Meaning:
m.sum(axis=1)
: Sum the numpy array along the rows m.sum(axis=0)
: Sum the numpy array along the columns np.concatenate([m.sum(axis=1), m.sum(axis=0)])
: Combine both the sums (along rows and columns) into t single numpy array np.unique(x)
: Find the number of unique elements in the numpy array x len(np.unique(np.concatenate([m.sum(axis=1), m.sum(axis=0)]))) == 1)
: Check the number of unique elements in the row wise sum and columns wise sum is 1. ie all the row wise sum and column wise sums are same. This is not as clever as the numpy answer, but it works
def magic_square(m):
# check size
for i in range(len(m)):
if len(m[i]) != len(m):
return False
# check row sums
for r in m:
if sum(r) != sum(m[0]):
return False
# check column sums
cols = [[r[c] for r in m] for c in range(len(m[0]))]
for c in cols:
if sum(c) != sum(m[0]):
return False
return True
m = [ [1,2,3,4]
, [5,6,7,8]
, [9,10,11,12]
, [13,14,15,16]
]
print(magic_square(m)) # False
m = [ [8,11,14,1]
, [13,2,7,12]
, [3,16,9,6]
, [10,5,4,15]
]
print(magic_square(m)) # True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.