Python set operations - complement union of set


I am in a Discrete Math course and am trying to replicate De Morgan's law of

Complement(B union C) = Complement(B) intersect Complement(C).

I tried searching for Python's ability to perform a complement on a set, but I didn't see much if anything.

So I just tried this in IDLE. Does this appear correct?

U = {'pink', 'purple', 'red', 'blue', 'gray', 'orange', 'green', 'yellow', 'indigo', 'violet'}
A = {'purple', 'red', 'orange', 'yellow', 'violet'}
B = {'blue', 'gray', 'orange', 'green'}
C = {'pink', 'red','blue','violet'}
Comp_B = U - B
Comp_C = U - C
Comp_Union_BC = Comp_B.intersection(Comp_C)
print(Comp_Union_BC)

Answer

The complement of a set is everything not in the set, but part of the 'universal set'. Without a definition of the universal set, you can't really give a standard-library definition of the complement of a set.

Moreover, the Python set type deals in sets of discrete objects, not a mathematical construct that could be infinitely large, such as all natural numbers. So Python doesn't support the general, nebulous and infinite idea of a single universal set.

For specific domains, if you can define the universal set in discrete terms, simply define your own complement() callable. For example, given a global definition of the universal set U, you can define the complement of a set a as the difference between U and that set:

U = {'pink', 'purple', 'red', 'blue', 'gray', 'orange', 'green', 'yellow', 'indigo', 'violet'}

def complement(a):
    # difference between a global universal set U and the given set a
    return U - a

or, simpler still:

complement = U.difference

Then just pass a set to complement() to test the hypothesis:

>>> # set | set == set union, set & set == set intersection
...
>>> complement(B | C) == complement(B) & complement(C)
True

So yes, your interpretation is correct, U - B produces the complement of B.