Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

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

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

What I want to find is a list

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

because the intersection is not empty once all the sets are put together.

For the example

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

the result should be

r = [(1, 5, 4, 2, 3, 6, 7), (8, 9)]

Hope the problem is clear. So what is the most elegant way to do this in python, if any?

Cheers

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...