Sub topic 3
Hash functions: turning keys into integers
This chapter assumes you can read basic Python, know what an array index is, and understand the modulo operator (%). It covers how a hash function turns a key into an integer and what makes one good or bad. Reducing that integer to a bucket index comes in the next chapter.
What a hash function does
An array can only be indexed by integers. Keys such as "apple" or (3, 4) are not integers. A hash function is a function that maps a key of any size to a fixed-size integer, called the hash value.
Required properties
A hash function used in a hash table must have these properties:
- Deterministic: the same key always gives the same hash value during one run of the program. Without this, you could never find an entry again.
- Consistent with equality: if two keys are equal, their hash values must be equal. The reverse is not required.
- Fast: it runs on every insert, lookup, and delete, so it should take time proportional to the key's size and no more.
- Well spread: different keys should give values spread across the whole integer range, so they land in different buckets.
A simple string hash
A common approach for strings is a polynomial hash. It processes characters one at a time and multiplies the running total by a small constant, here 31, before adding each character code.
def string_hash(s, size):
h = 0
for ch in s:
h = (h * 31 + ord(ch)) % size
return h
print(string_hash("apple", 8))
print(string_hash("apple", 8) == string_hash("apple", 8))This prints 2 and then True. The second line shows determinism. The % size inside the loop keeps the number small and reduces it to a bucket index at the same time.
The multiplication makes character position matter. Compare a hash that only adds character codes:
def sum_hash(s):
return sum(ord(c) for c in s)
print(sum_hash("listen"), sum_hash("silent"))Both words print 655. Every anagram collides, so a table keyed on words would put them all in one bucket. The polynomial version gives different values here because each letter is multiplied by a different power of 31.
Common mistakes
- Using only part of the key. Hashing just the first three characters sends every URL starting with
https://to the same value. - Hashing a mutable value. If a key changes after insertion, its hash changes and the entry becomes unreachable. The key requirements chapter returns to this.
- Comparing hash values across runs. Python randomizes
hash()for strings in each process, so the number printed today will differ tomorrow. Never store it in a file or depend on a specific value.
Using the built-in hash
In practice you call hash(key) and let the language handle the details. Python's hash() works for strings, numbers, and tuples of hashable items, and it raises TypeError for lists and dicts. The tables later in this tutorial use hash(key) % len(buckets) for exactly this reason.
Exercise
Why is sum(ord(c) for c in s) a poor hash function for words, and what change in string_hash fixes the problem?
Show answer
It ignores character order, so anagrams such as "listen" and "silent" get the same value and collide. Multiplying the running total by a constant (31) before adding each character makes the position of each character affect the result, so anagrams usually get different values.
Exercise
A key's hash value is 1,000,003 and the table has 8 buckets. Hash functions must be deterministic. What goes wrong if the same key later hashes to a different value?
Show answer
The key would map to a different bucket than the one where it was stored, so a lookup would look in the wrong place and report the key as missing, even though the entry is in the table.