你的测试第一检查后立即返回。为了测试矩阵是否反对称(斜对称),您需要继续检查,直到找到一对(i,j)为A[i][j] != -A[j][i]
。
它几乎总是更好的Python直接循环遍历容器中的项目,而不是使用索引。若要提高矩阵我们可以使用内置zip
功能:
def is_antisymmetric(m):
# Transpose matrix m
t = zip(*m)
#Check each row against each column
for row, col in zip(m, t):
#Test that each item in the row is the negative
# of the corresponding column item
for u, v in zip(row, col):
if u != -v:
return False
return True
# Test
data = (
# Not anti-symmetric
[[0, 1, 2],
[-1, 0, -2],
[2, 2, 3]],
# Anti-symmetric
[[0, 1, 2],
[-1, 0, -2],
[-2, 2, 0]],
)
for m in data:
for row in m:
print(row)
print(is_antisymmetric(m))
输出
[0, 1, 2]
[-1, 0, -2]
[2, 2, 3]
False
[0, 1, 2]
[-1, 0, -2]
[-2, 2, 0]
True
我们可以通过使用all
函数内部生成的表达使更紧凑的功能:
def is_antisymmetric(m):
return all([-u for u in col] == row for row, col in zip(m, zip(*m)))
all
函数只要发现ar就停止测试这不等于相应的列。 ==
测试还会在发现不匹配时立即停止将当前行与当前列进行比较,因此该代码与早期版本相同,只是效率更高一些。但是,如果您不习惯生成表达式,那么读起来可能不那么容易。 :)
FWIW,都在这个答案的代码运行在Python 2和Python 3中,它处理任何规模的方阵。
因为第一件事的0 – muddyfish
0 == -0和世界按预期工作。 –
A [0] [0] == -A [0] [0],因为A [0] [0] == 0 – tianwei