Если вы ищете только пересечения двух наборов, вы можете просто сделать вложенные циклы:
Set1 = {1,2,3,4,5}
Set2 = {4,5,6,7}
Set3 = {6,7,8,9,10}
Set4 = {1,8,9,15}
sets = [Set1,Set2,Set3,Set4]
for i,s1 in enumerate(sets[:-1]):
for j,s2 in enumerate(sets[i+1:]):
print(f"Set{i+1} and Set{i+j+2} = {s1&s2}")
# Set1 and Set2 = {4, 5}
# Set1 and Set3 = set()
# Set1 and Set4 = {1}
# Set2 and Set3 = {6, 7}
# Set2 and Set4 = set()
# Set3 and Set4 = {8, 9}
Если вы ищете пересечения любого числа этих наборов, то вы можете использовать комбинации () из itertools, чтобы получить набор индексов мощности и выполнить пересечение для каждой комбинации:
from itertools import combinations
for comboSize in range(2,len(sets)):
for combo in combinations(range(len(sets)),comboSize):
intersection = sets[combo[0]]
for i in combo[1:]: intersection = intersection & sets[i]
print(" and ".join(f"Set{i+1}" for i in combo),"=",intersection)
Set1 and Set2 = {4, 5}
Set1 and Set3 = set()
Set1 and Set4 = {1}
Set2 and Set3 = {6, 7}
Set2 and Set4 = set()
Set3 and Set4 = {8, 9}
Set1 and Set2 = {4, 5}
Set1 and Set3 = set()
Set1 and Set4 = {1}
Set2 and Set3 = {6, 7}
Set2 and Set4 = set()
Set3 and Set4 = {8, 9}
Set1 and Set2 and Set3 = set()
Set1 and Set2 and Set4 = set()
Set1 and Set3 and Set4 = set()
Set2 and Set3 and Set4 = set()