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)
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With