使用Python从树中提取所有可能的最长路径

时间:2013-04-30 14:29:17

标签: python graph python-2.7 tree pygraphviz

我有一个使用Pygraphviz生成的关键字树,如下所示。我将树的边缘作为元组列表。我正在寻找一种算法或最佳方法来从这棵树中提取所有可能的最长路径,以便它涵盖所有可能的关系。

由于我使用Pygraphviz,我正在寻找一种直接而简单的方法来实现这一目标。但看起来Pygraphviz没有这方面的选择。

edges = 
[('Sara', 'chocolate'),
('chocolate', 'loves'),
('oranges', 'chocolate'),
('Jessi', 'chocolate'),
('best', 'best'),
('friends', 'chocolate'),
('Aron', 'chocolate')]

enter image description here

预期结果:

[['Sara', 'chocolate', 'loves'],   
 ['oranges', 'chocolate', 'loves'],   
 ['Jessi', 'chocolate', 'loves'],  
 ['friends', 'chocolate', 'loves'],  
 ['Aron', 'chocolate', 'loves'],  
 ['Sara', 'chocolate', 'oranges'],  
 ['Sara', 'chocolate', 'Jessi'],  
 ['Sara', 'chocolate', 'friends'],  
 ['Sara', 'chocolate', 'Aron'],  
 ['oranges', 'chocolate', 'Jessi'],  
 ['oranges', 'chocolate', 'friends'],  
 ['oranges', 'chocolate', 'Aron'],  
 ['Jessi', 'chocolate', 'friends'],
 ['Jessi', 'chocolate', 'Aron'],  
 ['friends', 'chocolate', 'Aron'],
 ['best', 'best']]

我目前的代码:

from collections import defaultdict
import itertools
edges = [('Sara', 'chocolate'),
         ('chocolate', 'loves'),
         ('oranges', 'chocolate'),
         ('Jessi', 'chocolate'),
         ('best', 'best'),
         ('friends', 'chocolate'),
         ('Aron', 'chocolate')]
neighbors = {}
rev_neighbors = {}
for edge in edges:
    neighbors[edge[0]] = edge[1]

for edge in edges:
    neighbor = neighbors.get(edge[1])
    if neighbor:
        print edge[0], edge[1], neighbor

v = defaultdict(list)
for key, value in sorted(neighbors.iteritems()):
    v[value].append(key)
for key, value in v.iteritems():
    if not len(list(itertools.combinations(value, 2))) == 0:
        for item in list(itertools.combinations(value, 2)):
            print item[0], key, item[1]

P.S。:请忽略数字标签。

0 个答案:

没有答案