Chin Chin - 3 months ago 15
Python Question

Find edges of multiplicity larger than 2 in a NetworkX MultiGraph

I have a

MultiGraph
which can have multiple edges between any two nodes:

g = MultiGraph()
g.add_nodes_from([1,2,3,4,5,6])
g.add_edges_from([(1,2), (2,1), (1,2), (3,4), (5,6), (6,5), (3,5), (3, 5), (3, 5), (3, 5)])


How can I find all edges with multiplicity larger than 2 in this graph? I can do something like this:

for s in itertools.combinations(g.nodes(), 2):
e = g[s[0]].get(s[1], {})
if len(e) > 2:
print(s[0], s[1])


but it is too inefficient, so I'm looking for a better solution

Answer
for u in G.nodes():
    for neighbor in G.neighbors(u):
        if G.number_of_edges(u,neighbor)>2:
            print (u,neighbor)

Note - each such edge will be printed twice.

Comments