[course]06 —— sets

1. Quick Example

# A set is a data structure that can hold multiple elements in no particular order
# We cannot index into it, but we can iterate over it.
s = set([2,3,5])
print(3 in s)          # prints True
print(4 in s)          # prints False
for x in range(7):
    if (x not in s):
        print(x)       # prints 0 1 4 6

2. Creating Sets

1. Create an empty set

s = set()
print(s)     # prints set(), the empty set

2. Create a set from a list

s = set(["cat", "cow", "dog"])
print(s)     # prints {'cow', 'dog', 'cat'}

3. Create a statically-allocated set

4. Caution: { } is not an empty set!

3. Using Sets

4. Properties of Sets

Though sets are very similar to lists and tuples, they have a few important differences...

1. Sets are Unordered

2. Elements are Unique

3. Elements Must Be Immutable

4.Another example:

5. Sets are Very Efficient

The whole point of having sets is because they are very efficient, in fact O(1), for most common operations including adding elements, removing elements, and checking for membership.

5. How Sets Work: Hashing

Sets achieve their blazing speed using an algorithmic approach called hashing.

A hash function takes any value as input and returns an integer. The function returns the same integer each time it is called on a given value, and should generally return different integers for different values, though that does not always need to be the case. We actually don't need to build the hash function ourselves, as Python has one already, a built-in function called hash.

Python stores items in a set by creating a hash table, which is a list of N lists (called 'buckets'). Python chooses the bucket for an element based on its hash value, using hash(element) % n. Values in each bucket are not sorted, but the size of each bucket is limited to some constant K.

We get O(1) (constant-time) adding like so: 1. Compute the bucket index hash(element) % n -- takes O(1). 2. Retrieve the bucket hashTable[bucketIndex] -- takes O(1). 3. Append the element to the bucket -- takes O(1). We get O(1) (constant-time) membership testing ('in') like so: 1. Compute the bucket index hash(element) % n -- takes O(1). 2. Retrieve the bucket hashTable[bucketIndex] -- takes O(1). 3. Check each value in the bucket if it equals the element -- takes O(1) because there are at most K values in the bucket, and K is a constant. Q: How do we guarantee that each bucket is no larger than size K? A: Good question! If we need to add a (K+1)th value to a bucket, instead we resize our hashtable, making it say twice as big, and then we rehash every value, basically adding it to the new hashtable. This takes O(N) time, but we do it very rarely, so the amortized worst case remains O(1).

A practical example of how sets are faster than lists is shown below:

6. Some Worked Examples Using Sets

1. isPermutation(L)

2. repeats(L)

Last updated

Was this helpful?