【问题标题】:How to avoid maximum recursion depth in python with generators?python - 如何使用生成器避免python中的最大递归深度?
【发布时间】:2016-11-29 13:00:36
【问题描述】:

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

【问题讨论】:

  • 不,我说的是使用生成器来处理它们。这是一个例子。我正在使用下一个生成器,但仍然达到最大深度。
  • 如果您在使用小图(例如您的示例)时遇到此错误,则说明您有逻辑错误,而不是资源限制。除非图表有超过一千个节点,否则应该不是问题。
  • 你的确切程序在我的机器上运行得很好
  • @Navidad20 和 John:你们使用小例子是对的。事实上,它适用于像这样的小例子,但不适用于更大的例子。这正是我的问题,我如何处理更大的数据集(或在这种情况下的图表)?
  • for next in graph[vertex] - set(path): 行防止循环,但它不会阻止多次访问同一节点(在通过不同中间节点的路径上)。也许您可以维护一组访问过的节点,并且只通过以前未访问过的节点来扩展路径。

标签: python recursion generator breadth-first-search


【解决方案1】:

试试这个。它包括一个访问集。我还将变量名称“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

【讨论】:

  • 感谢您的尝试。但是,我仍然得到相同的最大递归深度错误。
  • 如果您可以提供一些示例数据来显示您的错误,我认为这对于帮助某人找到解决方案大有帮助。
  • 好的,我正在建立一个 github 存储库。给我 5 分钟。
  • 我找到了解决方案,John 和@Navidad20 你们是对的,保持访问减少了被压入堆栈的元素。谢谢各位,给您造成的困扰,深表歉意! :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
  • 2021-02-07
相关资源
最近更新 更多