0

Just an example:

set_0={0,3,4}
set_1={1,3,4}
set_2={1,5,23,8,24}
set_4={1,2,6,10}
set_5={1,60,34,2}
set_6={1,45,32,4}
set_7={1,6,9,14}
set_8={1,56,3,23}
set_9={1,34,23,3}
all_intersection=set.intersection(set_0,set_1,set_2,set_3,set_4, set_5, set_6, set_7, set_8, set_9)

gives empty set. Is there any way I can find the intersection among all possible combinations of 9 out of 10 sets in a pythonic way (perhaps without the brute force approach).

For this dataset I would expect to retrieve 1.

Caterina
  • 775
  • 9
  • 26

1 Answers1

1

Trying to call intersection on the class set is going to lead to errors, because the returned methods are descriptors.

Though, looks like you need to choose a set from which to form a basis of intersection. But, that intersection won't find the most common value, it will tell you which value is in each set at least once. The Counter class from collections can tell you which values are the most common.

from collections import Counter

set_0 = {0, 3, 4}
set_1 = {1, 3, 4}
set_2 = {1, 5, 23, 8, 24}
set_4 = {1, 2, 6, 10}  # you're missing set_3
set_5 = {1, 60, 34, 2}
set_6 = {1, 45, 32, 4}
set_7 = {1, 6, 9, 14}
set_8 = {1, 56, 3, 23}
set_9 = {1, 34, 23, 3}

my_sets = (set_0, set_1, set_2, set_4, set_5, set_6, set_7, set_8, set_9)
values_of_interest = set().union(*my_sets)

values_shared_among_all_sets = values_of_interest.intersection(*my_sets)
counter = Counter(item for collection in my_sets for item in collection)
the_5_most_common_values = counter.most_common(5)

print(f"values in all sets: {values_shared_among_all_sets}")
print(f"most common 5 values: {the_5_most_common_values}")

# this is the output
values in all sets: set()
most common 5 values: [(1, 8), (3, 4), (4, 3), (23, 3), (2, 2)]
aiootp
  • 154
  • 4