python - 测试网格是否为反对称 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
解决方案
您应该尽快返回 False 并在外部 while 循环结束时返回 True 以确保比较所有值对。
推荐阅读
- ios - 将手表应用程序添加到 Flutter iOS 应用程序
- manticore-search - Is json api for search only available for RT indices?
- r - Using separate() from tidyr to separate letter code into 4 variables in r
- javascript - componentDidMount() 期间的 setState
- regex - Regex comma delimited string with specific characters
- python - how to get around "This probably means that TCL was not installed properly"?
- meteor - Meteor custom CLI tool
- bash - syntax error near unexpected token `(' : output awk result as variable
- c++ - CUDA 写入其他经纱看不到的全局内存
- c# - Setting Filter on CollectionViewSource bound to ComboBox in WPF Automatically selects the first item