Sets
Sets
A set is a collection of distinct elements that are stored in a way that allows for quick access and retrieval. Sets are commonly used in computer science to store unique elements and perform set operations such as union, intersection, and difference.
Sets are implemented using hash tables in many programming languages, which allows for fast search and retrieval of elements. Sets are useful for removing duplicates from a list, checking for the presence of an element, and performing set operations.
Sets in Python
In Python, sets are implemented using the set
data structure, which is a built-in data type that stores unique elements. Sets are unordered collections of elements, and they do not allow duplicate values.
# Create a set
= set([1, 2, 3, 4, 5])
s
# Add an element to the set
6)
s.add(
# Remove an element from the set
3)
s.remove(
# Check if an element is in the set
if 4 in s:
print("Element found in set")
Set Operations
Sets support a variety of operations, including:
Union: Combines two sets to create a new set containing all unique elements from both sets.
Intersection: Finds the common elements between two sets and creates a new set with those elements.
Difference: Finds the elements that are in one set but not the other and creates a new set with those elements.
Subset: Checks if one set is a subset of another set.
Superset: Checks if one set is a superset of another set.
# Create two sets
= set([1, 2, 3, 4, 5])
s1 = set([4, 5, 6, 7, 8])
s2
# Union of two sets
= s1.union(s2)
union_set
# Intersection of two sets
= s1.intersection(s2)
intersection_set
# Difference of two sets
= s1.difference(s2)
difference_set
# Check if s1 is a subset of s2
= s1.issubset(s2)
is_subset
# Check if s1 is a superset of s2
= s1.issuperset(s2) is_superset
Time and Space Complexity
The time complexity of set operations is similar to hash table operations, with an time complexity of O(1) for search, insert, and delete operations. The space complexity of a set is O(n), where n is the number of elements in the set.
Union and intersection operations have a time complexity of O(n) in the worst case, where n is the number of elements in the larger set. The space complexity of set operations depends on the size of the input sets and the implementation of the set data structure.