我正在尝试编写一个Python函数,它可以在计算幻方时返回“True”或“False”。幻方是一个矩阵,它的行和、列和以及两条对角线的和都是相同的。(矩阵的一条对角线从左上角到右下角,另一条对角线从右上角到左下角。)
这是我的代码: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
但是,当我试图在一个幻方上测试我的代码时,该函数没有返回任何值:
^{pr2}$
我想知道是不是因为压痕?在