如何避免python中使用生成器的最大递归深度?

2024-05-05 18:38:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用BFS寻找最短路径,我很快就得到了这个RecursionError: maximum recursion depth exceeded in comparison,有什么建议可以用生成器避免它?或者让它迭代是唯一的好选择?在

代码如下:

def bfs_paths(graph, start, goal):
    queue = [(start, [start])]
    while queue:
        (vertex, path) = queue.pop(0)
        for next in graph[vertex] - set(path):
            if next == goal:
                yield path + [next]
            else:
                queue.append((next, path + [next]))

def shortest_path(graph, start, goal):
    try:
        return next(bfs_paths(graph, start, goal))
    except StopIteration:
        return None

使用示例:

^{pr2}$

Tags: pathin路径returnqueuedefstartgraph
1条回答
网友
1楼 · 发布于 2024-05-05 18:38:30

试试这个。它包括一个参观的集合。我还修改了“node”的变量名“next”,因为它是一个内置函数

def bfs_paths(graph, start, goal):
    visited = set()
    queue = [(start, [start])]
    while queue:
        vertex, path = queue.pop(0)
        visited.add(vertex)
        for node in graph[vertex]:
            if node in visited:
                continue
            elif node == goal:
                yield path + [node]
            else:
                queue.append((node, path + [node]))

def shortest_path(graph, start, goal):
    try:
        return next(bfs_paths(graph, start, goal))
    except StopIteration:
        return None

相关问题 更多 >