Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 708
TimmyTooTough Avatar asked May 15 '18 20:05

TimmyTooTough


People also ask

How do you find the union and intersection of two sets in Python?

Python's built-in data type set() and its helper functions can be leveraged to make sets and perform different operations on them. Union and intersection are the two of the most commonly performed operations on sets and can be found with the union() and intersection() functions.

Do Python sets have a union operation?

Python Set union() Method The union() method returns a set that contains all items from the original set, and all items from the specified set(s). You can specify as many sets you want, separated by commas.


1 Answers

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.

like image 95
Martijn Pieters Avatar answered Sep 25 '22 23:09

Martijn Pieters