The HashSet class provides a set data structure that stores unique elements. It is implemented using the HashTable class internally and provides O(1) average-case performance for insertions, deletions, and membership tests.
from dsa.hashset import HashSet# Create a hash set with default capacityhs = HashSet()# Create a hash set with custom capacityhs = HashSet(capacity=50)
A new HashSet instance containing the elements from the iterable
# Create from lisths = HashSet.from_list(["apple", "banana", "cherry"])# Create from tuplehs = HashSet.from_list(("x", "y", "z"))# Create from generatorhs = HashSet.from_list(x for x in range(10))# Create empty seths = HashSet.from_list()
from dsa.hashset import HashSet# Create a hash seths = HashSet()# Add itemshs.add("apple")hs.add("banana")hs.add("cherry")hs.add("apple") # Duplicate, no effect# Check membershipif "apple" in hs: print("Apple is in the set")# Remove itemhs.remove("banana")# Get sizeprint(f"Set size: {len(hs)}") # 2# Iterate over itemsfor item in hs: print(item)# Convert to listitems = hs.to_list()print(items)