【问题标题】:DFS on a graph using a python generator使用 python 生成器在图上进行 DFS
【发布时间】:2011-04-18 09:50:16
【问题描述】:

我正在使用生成器对图进行完整搜索,真实数据集相当大,这是我在一个小数据集上编写的部分代码:

class dfs: def __init__(self): self.start_nodes = [1,2] # not used, see below explanation self.end_nodes = [5,7] # not used, see below explanation _graph={ 1 : [4,5,6,2], 2 : [1,3,5], 4 : [1,5], 3 : [5,2], 5 : [3,1,4,6,2,7], 6 : [1,5], 7 : [5], } def __iter__(self): return self.find_path(self._graph, 2, 7) def find_path(self, graph, start, end, path=[]): path = path + [start] if start == end: yield path if not graph.has_key(start): return for node in graph[start]: if node not in path: for new_path in self.find_path(graph, node, end, path): if new_path: yield new_path d = dfs() print list(d)

运行时会按预期输出从“2”到“7”的所有路径:

[[2, 1, 4, 5, 7], [2, 1, 5, 7], [2, 1, 6, 5, 7], [2, 3, 5, 7], [2, 5, 7]]

我想做的是修改这个生成器,让它做同样的事情,除了我得到一组起点和终点的路径,即 self.start_nodes 和 self.end_nodes。

由于我的生成器是一个递归函数,因此很难在不同的起点和终点上循环,对此我有什么想法吗?

【问题讨论】:

标签: python


【解决方案1】:

也许我误解了你的问题,但在我看来你想用这样的东西替换你的 __iter__ 函数:

def __iter__(self):
    for start in self.start_nodes:
        for end in self.end_nodes:
            for path in self.find_path(self._graph, start, end):
                yield path

您可以找到有关生成器的更多信息in this question

【讨论】:

  • 那行得通,抱歉,现在看来很明显我想我需要更多地练习生成器(刚刚了解了它们)
猜你喜欢
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多