Search code examples
pythonlistsetdifference

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


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}


Solution

  • 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}