2

I have a list-

list_of_sets = [{0, 1, 2}, {0}]

I want to calculate the intersection between the elements of the list. I have thought about this solution:

a =  list_of_sets[0]

b =  list_of_sets[1]

c =  set.intersection(a,b)

This solution works as i know the number of the elements of the list. (So i can declare as many as variable i need like a,b etc.)

My problem is that i can't figure out a solution for the other case, where the number of the elements of the list is unknown.

N.B: the thought of counting the number of elements of the list using loop and than creating variables according to the result has already been checked. As i have to keep my code in a function (where the argument is list_of_sets), so i need a more generalized solution that can be used for any numbered list.

Edit 1:

I need a solution for all the elements of the list. (not pairwise or for 3/4 elements)

jfs
  • 399,953
  • 195
  • 994
  • 1,670
ni8mr
  • 1,725
  • 3
  • 31
  • 58

3 Answers3

5

If you wanted the intersection between all elements of all_sets:

intersection = set.intersection(*all_sets)

all_sets is a list of sets. the set is the set type.


For pairwise calculations,

This calculates intersections of all unordered pairs of 2 sets from a list all_sets. Should you need for 3, then use 3 as the argument.

from itertools import combinations, starmap
all_intersections = starmap(set.intersection, combinations(all_sets, 2))

If you did need the sets a, b for calculations, then:

for a, b in combinations(all_sets, 2):
    # do whatever with a, b
1

You want the intersection of all the set. Then:

list_of_sets[0].intersection(*list_of_sets[1:])

Should work.

Take the first set from the list and then intersect it with the rest (unpack the list with the *).

Dair
  • 15,910
  • 9
  • 62
  • 107
1

You can use reduce for this. If you're using Python 3 you will have to import it from functools. Here's a short demo:

#!/usr/bin/env python

n = 30
m = 5

#Find sets of numbers i: 1 <= i <= n that are coprime to each number j: 2 <= j <= m
list_of_sets = [set(i for i in range(1, n+1) if i % j) for j in range(2, m+1)]

print 'Sets in list_of_sets:'
for s in list_of_sets:
    print s
print

#Get intersection of all the sets
print 'Numbers less than or equal to %d that are coprime to it:' % n
print reduce(set.intersection, list_of_sets)

output

Sets in list_of_sets:
set([1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29])
set([1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29])
set([1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26, 27, 29, 30])
set([1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24, 26, 27, 28, 29])

Numbers less than or equal to 30 that are coprime to it:
set([1, 7, 11, 13, 17, 19, 23, 29])

Actually, we don't even need reduce() for this, we can simply do

set.intersection(*list_of_sets)
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182