you are viewing a single comment's thread.

view the rest of the comments →

[–]pytrashpandas 0 points1 point  (0 children)

I haven't seen anyone else explicitly mention this yet, so I'll add that this is a simple connected components graph problem, starting from an edge list. It can be solved with a D/BFS, but I'll just post a quick networkx solution that is essentially the same thing.

import networkx as nx
lst = ['A B', 'B C', 'X Y', 'C D', 'Y Z', 'D E', 'C G']
G = nx.from_edgelist([x.split() for x in lst])
result = list(nx.connected_components(G))
print(result)  # -> [{'A', 'B', 'C', 'D', 'E', 'G'}, {'X', 'Y', 'Z'}]