Set Operations in Python¶
CS 5001/5002 - Strings, Sequences & Sets
Code¶
#!/usr/bin/env python3
"""
Set Operations in Python
CS 5001/5002 - Strings, Sequences & Sets
This file demonstrates fundamental set operations:
- Union, intersection, difference, symmetric difference
- Complement operations with respect to a universe set
- De Morgan's laws verification
"""
# Define example sets
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
U = {1, 2, 3, 4, 5, 6, 7, 8} # Universe set
print(f"A = {A}")
print(f"B = {B}")
print(f"Universe U = {U}")
print()
# Union: A union B
union = A | B # or A.union(B)
print(f"A union B = {union}")
# Intersection: A intersect B
intersection = A & B # or A.intersection(B)
print(f"A intersect B = {intersection}")
# Difference: A - B
difference = A - B # or A.difference(B)
print(f"A - B = {difference}")
# Symmetric difference: A XOR B (elements in A or B, but not both)
sym_diff = A ^ B # or A.symmetric_difference(B)
print(f"A XOR B = {sym_diff}")
# Complement: complement of A (with respect to universe U)
complement_A = U - A
print(f"complement of A in U = {complement_A}")
# Verify De Morgan's laws
# not(A union B) = (not A) intersect (not B)
left_side = U - (A | B)
right_side = (U - A) & (U - B)
print(f"\nDe Morgan's Law verification:")
print(f"not(A union B) = {left_side}")
print(f"(not A) intersect (not B) = {right_side}")
print(f"Equal? {left_side == right_side}")
How to Use¶
- Copy the code above
- Save it as a
.pyfile (e.g.,set_operations.py) - Run it with:
python set_operations.py
Part of CS 5001/5002 - Strings, Sequences & Sets materials