使用python生成器在图上使用DFS
|
我正在使用生成器在图形上进行全面搜索,实际数据集相当大,这是我在小型数据集上编写的部分代码:
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。
由于我的生成器是一个递归函数,因此很难在不同的起点和终点循环,这让我无所适从吗?
没有找到相关结果
已邀请:
1 个回复
森含械
函数:
您可以在此问题中找到有关生成器的更多信息。