Skip to main content
 首页 » 编程设计

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

2024年10月17日8zhwl

我正在使用 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 

使用示例:

graph = {'A': set(['B', 'C']), 
         'B': set(['A', 'D', 'E']), 
         'C': set(['A', 'F']), 
         'D': set(['B']), 
         'E': set(['B', 'F']), 
         'F': set(['C', 'E'])} 
 
shortest_path(graph, 'A', 'F') # ['A', 'C', 'F'] 

请您参考如下方法:

试试这个。它包括一个访问集。我还将变量名“next”修改为“node”,因为它是一个内置函数

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