Finding the intersection between several sets in a list

Viewed 30

I have a list containing several sets {} with different names and string values.

eg.

set1 = {"a", "santa", "clock"}
search = {"why", "is", "santa", "nice"}

list_of_sets = [set1, search]

I want to find the intersection between the sets in the list through a function:

def intersection_between_sets_from_list(list_of_sets):
    """ find the intersection between the sets here"""
    return intersection_strings

any idea what code to use in """ find the intersection between the sets here""".

1 Answers

If you want find the intersection between all sets in the list you could be iterate on list_of_set and find the intersection between the current set and your temporal set like this:

tmp = list_of_sets[0]
for e in list_of_sets:
    tmp = tmp.intersection(e)

but this operation on python language could be do:

reduce(lambda x, y: x.intersection(y), list_of_sets)
Related