首页 > 解决方案 > 测试网格是否为反对称 python 的函数的结果不正确

问题描述

我的大多数测试用例都返回了正确的结果,但是当它应该为 false 时,这个返回的是 True:

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

谁能告诉我我的代码有什么问题?谢谢!

def antisymmetric(A):
    n = len(A)
    i = 0
    while i < n:
        j = 0
        while j < n:
            if A[i][j] == -A[j][i]:
                return True
            else:
                return False
            j += 1
        i += 1
# Test Cases:

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

print antisymmetric([[0, 0, 0],
                 [0, 0, 0],
                 [0, 0, 0]])
#>>> True

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

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

标签: pythonpython-2.7listwhile-loop

解决方案


您应该尽快返回 False 并在外部 while 循环结束时返回 True 以确保比较所有值对。


推荐阅读