Reputation: 18329
You have an arbitrary number of sets, for example:
sets = [{1,2,3}, {3,4,5}, {5,6,7}]
You want to see if any value in one set is also in any other set. What is the most efficient way to do this?
Currently I have the following:
index = 0
for set in sets:
for i in range(index + 1, len(sets)):
print set, sets[i], set & sets[i]
index += 1
Which results in:
set([1, 2, 3]) set([3, 4, 5]) set([3])
set([1, 2, 3]) set([5, 6, 7]) set([])
set([3, 4, 5]) set([5, 6, 7]) set([5])
Upvotes: 0
Views: 52
Reputation: 142
set.intersection(*list_of_sets)
will unpack your list of sets and find intersection.
Upvotes: -1
Reputation: 77407
Its a minor tweak but you can let itertools.combinations
generate the set pairs for you. This example is python 3 so the representations look a little different, but should work fine in 2.x
>>> import itertools
>>> sets = [{1,2,3}, {3,4,5}, {5,6,7}]
>>> for s1,s2 in itertools.combinations(sets,2):
... print(s1, s2, s1 & s2)
...
{1, 2, 3} {3, 4, 5} {3}
{1, 2, 3} {5, 6, 7} set()
{3, 4, 5} {5, 6, 7} {5}
Upvotes: 2