Standard Sets in Python¶
CS 5001/5002 - Strings, Sequences & Sets
Code¶
#!/usr/bin/env python3
"""
Filename: standard_sets_python.py
Description: Standard Sets in Python
CS 5001/5002 - Strings, Sequences & Sets
This script demonstrates how to create and work with standard mathematical sets
in Python, including empty sets, natural numbers, and integers.
"""
def main():
# Empty set
empty_set = set() # Note: {} creates empty dict, not empty set
print(f"Empty set: {empty_set}")
print(f"Cardinality of empty set: {len(empty_set)}")
# Set containing empty set (different from empty set!)
set_with_empty = {frozenset()} # Contains one element: the empty set
print(f"Set containing empty set: {set_with_empty}")
print(f"Cardinality: {len(set_with_empty)}") # 1, not 0!
# Natural numbers (finite subset for demonstration)
natural_numbers = set(range(10)) # {0, 1, 2, ..., 9}
print(f"First 10 natural numbers: {natural_numbers}")
# Positive integers (excluding 0)
positive_integers = set(range(1, 11)) # {1, 2, 3, ..., 10}
print(f"First 10 positive integers: {positive_integers}")
# Integers including negatives
integers = set(range(-5, 6)) # {-5, -4, ..., 4, 5}
print(f"Integers from -5 to 5: {integers}")
if __name__ == "__main__":
main()
How to Use¶
- Copy the code above
- Save it as a
.pyfile (e.g.,standard_sets_python.py) - Run it with:
python standard_sets_python.py
Part of CS 5001/5002 - Strings, Sequences & Sets materials