有谁知道如何实现一个函数来确定矩阵是否是魔方?例如:
>>> is_magic_square([[2, 7, 6], [9, 5, 1], [4, 3, 8]])
True
这是我的行总和方法:
def row_sum(rows):
return (list (map (lambda x: sum(x), rows)))
我想知道如何获得两个对角线的总和。
答案 0 :(得分:-1)
rows = all(sum(row) == sum(matrix[0]) for row in matrix)
cols = all(sum(col) == sum(map(list, zip(*matrix))[0]) for col in matrix)
diag1 = sum(matrix[i][i] for i in range(3)) == sum(matrix[0])
diag1 = sum(matrix[2-i][i] for i in range(3)) == sum(matrix[0])
print rows and cols and diag1 and diag2 # magic or not