2016-08-25 90 views
-3
def antisymmetric(A): 
    #Write your code here 
    for i in range(3): 
     for j in range(3): 
      if A[i][j] == -A[j][i]: 
       return True 
      else: 
       return False  


# Test Cases: 

print antisymmetric([[0, 1, 2], 
        [-1, 0, -2], 
        [2, 2, 3]]) 
#>>> False 

令人驚訝的是上面的測試情況下返回True對於這條巨蟒2.7編碼,誰能告訴我原因嗎?爲什麼這個python-2.7測試用例返回True?

+0

因爲第一件事的0 – muddyfish

+2

0 == -0和世界按預期工作。 –

+0

A [0] [0] == -A [0] [0],因爲A [0] [0] == 0 – tianwei

回答

1

你在我返回True = 0 J = 0循環不直到

1

我想這是因爲你從函數的第一次測試後,退還結束時執行。 只有當您可以排除矩陣反對稱的可能性後,您纔可能想要返回。 IE瀏覽器。 onley在循環中返回false,並在循環結束後返回true。

+0

你應該更加自信地陳述你的答案!不要說「我猜」和「可能」。並使用拼寫檢查器。 :) –

3

它是在I = 0和j = 0

改性溶液返回true:

def antisymmetric(A): 
    for i in range(3): 
     for j in range(3): 
      if A[i][j] != -A[j][i]: 
       return False 
    return True 
2

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

相關問題