giving the paired nodes and a list of random nodes, find and group the nodes that are connected in python
Question:
saying I have a list of pairs like
pairs = [[0,10],[0,1],[0,2],[1,7],[2,3],[2,4],[3,8],[4,5],[5,6],[8,9]]
and a list
a = [3,4,5,6,8,9]
.
Based on given pairs, how to group list, a, into [[3,8,9],[4,5,6]]
? Any idea? Thanks in advance.
Answers:
You can use networkx for this, with the subgraph
and connected_components
methods:
import networkx as nx
pairs = [[0,10],[0,1],[0,2],[1,7],[2,3],[2,4],[3,8],[4,5],[5,6],[8,9]]
a = [3,4,5,6,8,9]
G = nx.from_edgelist(pairs)
out = list(nx.connected_components(G.subgraph(a)))
Output: [{3, 8, 9}, {4, 5, 6}]
saying I have a list of pairs like
pairs = [[0,10],[0,1],[0,2],[1,7],[2,3],[2,4],[3,8],[4,5],[5,6],[8,9]]
and a list
a = [3,4,5,6,8,9]
.
Based on given pairs, how to group list, a, into [[3,8,9],[4,5,6]]
? Any idea? Thanks in advance.
You can use networkx for this, with the subgraph
and connected_components
methods:
import networkx as nx
pairs = [[0,10],[0,1],[0,2],[1,7],[2,3],[2,4],[3,8],[4,5],[5,6],[8,9]]
a = [3,4,5,6,8,9]
G = nx.from_edgelist(pairs)
out = list(nx.connected_components(G.subgraph(a)))
Output: [{3, 8, 9}, {4, 5, 6}]