Sub topic 2
Why hash tables need hash functions
This chapter assumes you can read basic Python, use the modulo operator, and know what a dictionary (a map from keys to values) does. It explains the job a hash function does inside a hash table.
The problem a hash table solves
A list of key-value pairs can be searched by comparing your key against every entry. That takes time proportional to the number of entries. An array can be read at any position in constant time, but only if you know the position.
A hash table combines the two ideas. It keeps an array of slots called buckets. A hash function turns the key into an integer, and that integer picks the bucket. You no longer search for the key. You compute where it must be.
A minimal hash table
This table uses chaining. Each bucket is a list that holds every pair whose key maps to it. The hash function is a parameter so you can swap it.
class ChainedTable:
def __init__(self, buckets=8, hash_fn=hash):
self.buckets = [[] for _ in range(buckets)]
self.hash_fn = hash_fn
def _bucket(self, key):
return self.buckets[self.hash_fn(key) % len(self.buckets)]
def put(self, key, value):
bucket = self._bucket(key)
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
def get(self, key):
for k, v in self._bucket(key):
if k == key:
return v
raise KeyError(key)
good = ChainedTable()
bad = ChainedTable(hash_fn=lambda key: 0)
for word in ["apple", "pear", "plum", "fig", "kiwi", "lime"]:
good.put(word, len(word))
bad.put(word, len(word))
print(good.get("plum"))
print([len(b) for b in good.buckets])
print([len(b) for b in bad.buckets])The first print shows 4, so both lookups work. The bad table uses a hash function that always returns 0. It is still correct, because every key lands in bucket 0 and get finds it there. But that bucket now holds all six pairs, so each lookup scans a list. The table has become the slow linear search it was meant to replace. The exact bucket sizes of good vary between runs, because Python randomizes string hashes per process.
What the table requires from the hash function
The table relies on three facts about the hash function.
- It is deterministic.
putandgetmust compute the same bucket for the same key. If the hash changed between calls, a stored pair could never be found again. - It spreads keys out. Lookup cost is the length of one bucket. Evenly spread keys keep buckets short, so lookups stay close to constant time.
- It is fast. The hash runs on every insert, lookup, and delete. A slow hash adds its cost to every operation.
Correctness depends only on the first fact. Performance depends on the other two. The next chapter looks at them in detail.
Common mistakes
- Hashing a mutable key, such as a list, and then changing it. The new hash points to a different bucket, so the stored pair is lost. This is why Python refuses to hash lists.
- Assuming the hash alone identifies a key. Two different keys can share a bucket, so the table must still compare keys.
- Relying on a particular hash value across program runs. Python's string
hashchanges between processes, so never save it to disk.
Exercise
In the bad table above, every key hashes to 0. Does get return wrong answers, or does it only become slow? Explain which hash property is violated.
Show answer
It only becomes slow. get still scans bucket 0 and compares keys, so it finds the right value. The constant function is deterministic, but it violates uniformity, so one bucket holds every pair and lookups cost time proportional to the number of keys.