你的測試第一檢查後立即返回。爲了測試矩陣是否反對稱(斜對稱),您需要繼續檢查,直到找到一對(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