-1

I have sets

{1, 2, 3, 4}
{2, 3, 4, 5}
{3, 4, 5, 6}
{4, 5, 6, 7}
{5, 6, 7, 8} 

I need to intersect sets start from first. I mean that I should to intersect

{1, 2, 3, 4}
{2, 3, 4, 5}
{3, 4, 5, 6}

next

{2, 3, 4, 5}
{3, 4, 5, 6}
{4, 5, 6, 7}

and

{3, 4, 5, 6}
{4, 5, 6, 7}
{5, 6, 7, 8}

How can I do it in the loop? I know that I can use set1 & set2 & set3, but I don't know how can I do it with next set2 & set3 & set4 etc?

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
NineWasps
  • 2,081
  • 8
  • 28
  • 45

2 Answers2

2

First you need all your sets in a list, then iterate over your list in parallel with the zip-function:

sets = [
    {1, 2, 3, 4},
    {2, 3, 4, 5},
    {3, 4, 5, 6},
    {4, 5, 6, 7},
    {5, 6, 7, 8},
]

for s1, s2, s3 in zip(sets, sets[1:], sets[2:]):
    print(s1 & s2 & s3)

or more general:

AMOUNT_OF_SETS_TO_INTERSECT = 3
for sets_to_intersect in zip(*(sets[i:] for i in range(AMOUNT_OF_SETS_TO_INTERSECT))):
    print(set.intersection(*sets_to_intersect))
Daniel
  • 42,087
  • 4
  • 55
  • 81
0

If you are looking to find ways to do intersections of multiple sets, then this page has the answer, which basically tells you to use set.intersection() function

If you don't know how to put your sets inside a list and then traverse through it, it's a different question, which is basic Python.

In Python, you can put objects (including sets) inside a list and traverse through it as follows:

# Build the list of sets
set_list = []
for i in range(1, 6):
    set_list.append(set([i, i+1, i+2, i+3]))

# Now set_list contains the set (1,2,3,4), (2,3,4,5), ..., (5,6,7,8)

# Traverse and do set intersection
for i in range(len(set_list)-2):
    intersection = set.intersection(set_list[i], set_list[i+1], set_list[i+2])
    print(intersection)

# Will print:
# set([3, 4])
# set([4, 5])
# set([5, 6])
Community
  • 1
  • 1
justhalf
  • 8,960
  • 3
  • 47
  • 74