使用python networkx模块在图中查找链

时间:2015-05-05 08:28:49

标签: python networkx

我有一个包含节点和边列表的图表

nodes=['a','b','c','d','e','f','g'] 
G.add_edges_from ([('a','f'),('a','d'),('a','b'),('a','e'),('b','g'),
                   ('b','e'),('b','c'),('c','b'),('c','d'),('d','a'),
                   ('d','c'),('e','b'),('e','a'),  ('f','a'),('g','b')]. 

我的问题是识别每个节点的邻居,我使用G.neighbors(node[i])

确定了这些邻居

我得到了结果

a=>['e', 'b', 'f', 'd']
b=>['e', 'c', 'g', 'a']
c=>['b', 'd']
d=>['c', 'a']
e=>['b', 'a']
f=>['a']
g=>['b'].

现在我必须将链排序为f <=d <=b,将另一个链排序为g<=c<=a,这意味着将它们排序为另一个链的子集。 f是d的一个子集,它是b的子集。

e是连接这两个链的中心节点,我手动计算了它。问题是我没有得到这个链,如何循环它们?

1 个答案:

答案 0 :(得分:0)

据我所知,您希望列出所有节点,这些节点是邻居的子集。因此,对于您的样本图,链应该是:

f&lt; = d&lt; = b,g&lt; = c&lt; = a(你提到的)加上你没有提到的g&lt; = e。我假设你不想拥有现有链的子集;存储g&lt; = c&lt; = a但不是c&lt; = a

这是我解决问题的方法(我评论它尽可能清楚):

tmp = [] # temporary storage for chains
chains = [] # stores all found chains
nodes = G.nodes() # save the labels of nodes
prev_node =  None # Holds the node which other nodes will be checked if they are a subset of.
for i in xrange(len(nodes)): # each node is considered as a superset and others will be compared to it
    tmp.append(nodes[i]) # append this node as the head of the chain
    prev_node = nodes[i] # store it to compare other nodes to it
    for j in xrange (i+1,len(nodes)): # looping the rest of the nodes
        if set(G.neighbors(nodes[j])).issubset(set(((G.neighbors(prev_node))))) : # if it is a subset
            tmp.append(nodes[j]) # append to the chain
            prev_node = nodes[j] # store to check if the rest of the nodes are subset of this one

    if not (is_subset(chains,tmp)): # After finishing the chain check it is not a subset of an already created chain
        chains.append(list(reversed(tmp))) # add it to the chains
    tmp =[] # reset
    prev_node = None
print chains

is_subset函数是一个简单的函数,如果tmp已经是链的子集(以排除它),则返回true:

def is_subset(chains,tmp):
    for i in xrange(len(chains)):
        if set(tmp).issubset(chains[i]):
                return True
    return False