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

后端 未结 3 1186
粉色の甜心
粉色の甜心 2020-12-02 01:01

here is the problem: I have a list of tuples (could be sets as well if needed). For instance:

a = [(1, 5), (4, 2), (4, 3), (5, 4), (6, 3), (7, 6)]

3条回答
  •  情话喂你
    2020-12-02 01:13

    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)]
    

提交回复
热议问题