python - 寻找最短路径时的最大递归深度超出错误
问题描述
我试图找到从源到目标的最短点,但出现错误:
RecursionError: maximum recursion depth exceeded while calling a Python object
这是我的代码,其中 neighbors_for_id 返回源邻居的 id 列表:
"""
Returns the shortest list of person_ids that connect the source to the target.
If no possible path, returns None.
"""
visited = set()
path = []
if source == target:
return path
while source != target:
destinations = neighbors_for_id(source)
for neighbor in destinations:
path.append(neighbor)
if neighbor == target:
return path
if neighbor not in visited:
visited.add(neighbor)
source = neighbor
shortest_path(source, target, visited)```
解决方案
2件事:
您当前(错误地)在进入函数时将“已访问”重置为空集,即使您将其作为来自内部调用的参数传递。这可能会导致最大深度问题,因为它现在可以在 2 个邻居之间“乒乓”或跟随图形中的循环。
当您在外部调用该函数以启动它时,只需传递一个空集:
shortest_path(source, target, set())
您正在对路径列表执行类似的操作。您需要在递归中传递它,以便后续步骤将添加到不断增长的列表中,而不是在函数中重置它。因此,您可能最终会得到一个包含路径的新函数签名。
您可以使用默认值对其进行一些清理,例如:
def shortest_path(source, target, visited=set(), path=list() ):
推荐阅读
- c - 在 OpenSSL 中实现 PQC 算法
- c# - 包括 Azure 源 DLL 包的调试符号
- html - 没有边界的CSS浮动问题
- wordpress - 显示附加到自定义帖子类型的用户 - ACF
- python - 在张量流中,为什么 tf.equal(tf.size(x), 0) 条件即使对于空张量也总是 False?
- c++ - 如何减少浮点变量直到它正好为零
- r - 如何解决 geom_errorbar 中的以下错误:“需要以下缺失的美学:x 或 xmin 和 xmax”?
- javascript - 如何动态计算和限制可滚动溢出 div 的宽度?
- python - 无法从 python rpy2 包加载 robjects 模块
- xamarin - Xamarin webview 如何从 SVG 源捕获工具提示文本?