Home > database >  How to create a new set of all elements that are in only one of multiple sets?
How to create a new set of all elements that are in only one of multiple sets?

Time:11-14

I need the code to:

  1. scan all elements of four different sets
  2. put values that only appear uniquely in one set and not the others inside a new set

Example:

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

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

C{1,3,4,7}

D{1,8,9}

Set E would look like: {5,6,7,8,9}

For context: a different part of the question was to make a set with elements of numbers that were divisible by 3,5,7 and 11. This is code from that part of the question, and now I'm looking to do this new part. I'm sure there's a better way to do this however I'm only 2 months in of self-teaching and I would like to just know what to do for this question.

set3_list=[]  
for x in range(1,501):
    if(x%3==0):
        set3_list.append(x)
        
set5_list=[]
for y in range(1,501):
    if(y%5==0):
        set5_list.append(y)
        
set7_list=[]
for z in range(1,501):
    if(z%7==0):
        set7_list.append(z)
        
set21_list=[]
for a in range(1,501):
    if(a%11==0):
        set21_list.append(a)
        
s3=set(set3_list)
s5=set(set5_list)
s7=set(set7_list)
s21=set(set21_list)

CodePudding user response:

How about pooling all the sets (allowing for duplicates), counting the elements, and then take elements that occur only once?

import itertools
import collections

A = {1,2,3,4,5}
B = {1,2,3,4,6}
C = {1,3,4,7}
D = {1,8,9}

cnt = collections.Counter(itertools.chain(A, B, C, D))
E = {k for k, v in cnt.items() if v == 1}
print(E) # {5, 6, 7, 8, 9}

If you are somewhat reluctant to import modules, the following is equivalent:

A = {1,2,3,4,5}
B = {1,2,3,4,6}
C = {1,3,4,7}
D = {1,8,9}

cnt = {} # prepare an empty list
for s in [A, B, C, D]: # loop over sets
    for x in s: # for each element in set s
        cnt[x] = cnt.get(x, 0)   1 # increment the counter

E = set(k for k, v in cnt.items() if v == 1) # set consisting of singleton elements
print(E) # {5, 6, 7, 8, 9}

CodePudding user response:

One way to do this is to unpack all the sets into a list. Then iterate over a union of them all getting their counts:

a = {1,2,3,4,5}
b = {1,2,3,4,6}
c = {1,3,4,7}
d = {1,8,9}

joined = [*a, *b, *c, *d]

result = {i for i in set.union(a, b, c, d) if not joined.count(i) - 1}

{5, 6, 7, 8, 9}

This can be made more efficient if you use collections.Counter for joined and itertools.chain:

from collections import Counter

result = {i for i, c in Counter(chain(a, b, c, d)).items() if c == 1}

CodePudding user response:

You could loop on sets and accumulate a unique and common set to extract the desired result:

A={1,2,3,4,5}    
B={1,2,3,4,6}    
C={1,3,4,7}    
D={1,8,9}

unique,common = set(),set()
for S in (A,B,C,D):
    unique = (unique|S) - (S&common) # add set, remove duplicates
    common |= S                      # track seen items
    
print(unique)
{5, 6, 7, 8, 9}
  • Related