Subset Relationships in Python¶
CS 5001/5002 - Strings, Sequences & Sets
Code¶
#!/usr/bin/env python3
"""
Filename: subset_relationships.py
Description: Subset Relationships in Python
CS 5001/5002 - Strings, Sequences & Sets
This script demonstrates how to test subset relationships in Python using
built-in methods and operators.
"""
def main():
# Define our sets
S = {1, 2, 3}
A = {2}
B = {1, 2}
C = {1, 2, 3}
print(f"S = {S}")
print(f"A = {A}")
print(f"B = {B}")
print(f"C = {C}")
# Test subset relationships
print(f"A subset S: {A.issubset(S)}") # True
print(f"B subset S: {B.issubset(S)}") # True
print(f"C subset S: {C.issubset(S)}") # True
# Proper vs improper subsets
print(f"A proper subset S: {A < S}") # True (proper subset)
print(f"C proper subset S: {C < S}") # False (equal sets)
print(f"C = S: {C == S}") # True (same set)
# Every set is a subset of itself
print(f"S subset S: {S.issubset(S)}") # True
# Empty set is subset of every set
empty = set()
print(f"empty subset S: {empty.issubset(S)}") # True
print(f"empty subset A: {empty.issubset(A)}") # True
if __name__ == "__main__":
main()
How to Use¶
- Copy the code above
- Save it as a
.pyfile (e.g.,subset_relationships.py) - Run it with:
python subset_relationships.py
Part of CS 5001/5002 - Strings, Sequences & Sets materials