Find sets of disjoint sets from a list of tuples or sets in python

These are the connected components of a graph, and can be found using a graphing library such as networkx. For your second example:

>>> edges = [(1, 5), (4, 2), (4, 3), (5, 4), (6, 3), (7, 6), (8, 9)]
>>> graph = nx.Graph(edges) 
>>> [tuple(c) for c in nx.connected_components(graph)]
[(1, 2, 3, 4, 5, 6, 7), (8, 9)]

Leave a Comment