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.
Asked
Active
Viewed 32 times
-2

chrslg
- 9,023
- 5
- 17
- 31

ying zhang
- 1
- 3
-
Here is the Wikipedia artivle on graph components. It has everything you need. https://en.wikipedia.org/wiki/Component_(graph_theory) – ravenspoint Dec 07 '22 at 22:53
-
Does this answer your question? [How to find Strongly Connected Components in a Graph?](https://stackoverflow.com/questions/33590974/how-to-find-strongly-connected-components-in-a-graph) – ravenspoint Dec 07 '22 at 22:55
1 Answers
1
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}]

mozway
- 194,879
- 13
- 39
- 75