python - 为什么只循环访问第一行?
问题描述
我将尝试从 2d 数组中查找元素,其中对每一行的元素进行排序。我使用 for 循环访问该行,然后在每一行中应用二进制搜索。但是 for 循环卡在第 1 行。
def searchMatrix(self, matrix, target) -> bool:
m = len(matrix)
print(m)
for i in range(m):
print(i)
if len(matrix[i]) == 1:
if matrix[i][0] == target:
return True
else:
return False
else:
start = 0;
end = len(matrix[0]) - 1
while start <= end :
mid = round((start+end)/2)
if(matrix[i][mid] == target):
return True
elif matrix[i][mid] > target:
end = mid - 1
elif matrix[i][mid] < target:
start = start + 1
return False
我的输出:
3
0
但输出应该是
3 0 1 2
解决方案
在您的循环中,所有条件都将导致一条return
语句,因此该函数将在第一次迭代中退出。您可以删除所有return False
并添加一个作为函数的最后一条语句:
def searchMatrix(self, matrix, target) -> bool:
m = len(matrix)
print(m)
for i in range(m):
print(i)
if len(matrix[i]) == 1:
if matrix[i][0] == target:
# Only exit the function if you find the target
return True
else:
start = 0;
end = len(matrix[0]) - 1
while start <= end :
mid = round((start+end)/2)
if(matrix[i][mid] == target):
# Only exit the function if you find the target
return True
elif matrix[i][mid] > target:
end = mid - 1
elif matrix[i][mid] < target:
start = start + 1
# Otherwise, keep iterating
# Since all rows were searched, exit the function
return False
推荐阅读
- swift - 我们是否需要 Aruco Marker 在手机中使用 .yml 文件?
- ruby-on-rails - Rails 5 - 如何在资产管道中包含所有供应商资产?
- elixir - 将列表转换为以前两个字母为索引的映射
- python - Python子进程调用()不执行shell命令
- r - 启动 RStudio 时如何删除包的自动加载?
- angular - 模板文件中只允许使用数组和可迭代对象。异常行为
- c++ - 在 C++ 中使用子级列表的通用树中添加一个节点并查找两个给定节点之间的路径成本
- python - 运行statsmodels马尔可夫回归时如何解决“参数不具有兼容的形状”
- python - 如何在特定目录(包括其子目录)中列出所有文件及其大小和创建日期?
- html - 用于响应式网格设计的更宽宽度的适当边距填充