我的大多数测试用例都返回了正确的结果,但是当它应该为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
答案 0 :(得分:1)
您应该尽快返回False并在外部while循环结束时返回True,以确保比较所有值对。
答案 1 :(得分:1)
def antisymmetric(l):
for i in range(len(l)):
for j in range(len(l[i])):
if l[i][j] != -l[j][i] and i != j:
return False
return True
要评估矩阵是否是反对称的,你需要检查所有的情况,因此你应该检查负面条件,如果测试不满足它,任何元素立即返回False
如果是反对称的,它将评估所有测试用例,如上所示,如果for循环结束,函数将返回True
。
您的测试结果失败,因为您仅在匹配一个条件后立即返回True。
您的循环将i=0, j=0
与A[0][0]
匹配0
而0 == -0
将评估True
并且您立即返回它,因此它会给您不必要的结果
此外,您还需要跳过对角元素,因为它不会发生变化