Sub topic 6
Hash functions: turning keys into integers
This chapter assumes you can write basic Python, know what a list index is, and have a rough idea of Big-O notation. It covers the hash function, the first piece of a hash table.
What a hash function does
A hash table stores entries in an array, and an array can only be indexed by integers. Keys are usually strings, tuples or objects. A hash function bridges the gap. It takes a key and returns an integer, called the hash code.
The table then reduces that integer to a valid array position, usually with a modulo. How the table uses the position is the subject of the next chapter. Here we only look at how keys become integers.
print(hash(42))
print(hash("cat") == hash("cat")) # True within one run
print(hash((1, 2)) == hash((1, 2))) # TrueInteger hashes in CPython are the integer itself for small values. String hashes are large numbers that change from one program run to the next.
Properties a good hash function needs
- Deterministic. The same key must give the same hash every time within a run. If it did not, a stored key could never be found again.
- Consistent with equality. If
a == b, thenhash(a) == hash(b). The reverse does not need to hold. - Well spread. Different keys should land on many different integers, so entries do not pile up in a few buckets.
- Cheap to compute. Hashing runs on every lookup, insert and delete. A slow hash makes every operation slow.
Two different keys may share a hash code. That is allowed and unavoidable, because there are far more possible keys than integers. Such a clash is a collision, covered in a later chapter.
A simple hash function for strings
Strings are usually hashed by mixing in each character in turn. This version multiplies a running value by a constant and adds the next character code.
def simple_string_hash(s, modulus=2**32):
h = 0
for ch in s:
h = (h * 31 + ord(ch)) % modulus
return h
for word in ["cat", "act", "tac"]:
print(word, simple_string_hash(word))The multiplication makes character position matter. Without it, a plain sum of character codes would give the same value for "cat", "act" and "tac", and every anagram would collide.
The cost grows with the length of the string, so hashing a key is O(k) for a key of length k. When people say a lookup is O(1), they mean it does not grow with the number of entries. It still depends on the size of the key.
From hash code to bucket index
A hash code can be huge or negative, so the table maps it into the array range.
def bucket_index(key, bucket_count):
return hash(key) % bucket_count
print(bucket_index("cat", 8))
print(bucket_index(("a", 1), 8))In Python, % with a positive divisor always returns a value from 0 to bucket_count - 1, even for negative hashes. In some other languages, the remainder of a negative number is negative, so those implementations mask the sign bit or use a bit mask instead.
Common errors
- Assuming hashes are unique. Equal hashes do not mean equal keys. The table must still compare keys with
==. - Relying on hash values for ordering. They look random and change between runs for strings.
- Writing
__eq__without a matching__hash__. Python sets__hash__toNonewhen you define__eq__alone, so instances become unusable as keys. - Hashing on fields that change. The hash then changes while the key is stored. A later chapter explains the effect.
Exercise
Two strings have the same hash code. Does the table treat them as the same key? Why must the table still check equality?
Show answer
No. Equal hash codes only show the keys might be equal. Different keys can collide, so the table compares the keys with == to confirm a match.
Exercise
Why does the simple string hash above use h * 31 instead of just adding ord(ch)?
Show answer
Plain addition ignores character order, so anagrams like "cat" and "act" would get the same hash. Multiplying the running value before adding each character makes position affect the result.