Edexcel International Advanced Level Computer Science, point 18.2.4
A hash algorithm (hash function) turns a key into a table index (14.1.2). In Unit 4 you must be able to select and use an appropriate one, and amend and write it. Check the PLS for exact detail.
What a good hash algorithm does
| Property | Meaning |
|---|---|
| Deterministic | The same key always gives the same index |
| Within range | The index is from 0 to size - 1 (use % size) |
| Even spread | Keys are spread across all buckets, so few collisions |
| Fast | Cheap to calculate |
| Uses the whole key | Every part affects the result |
A table size that is a prime number often spreads keys better, because patterns in the keys then share fewer factors with the size.
Algorithm 1: sum of character codes
Add the code of each character, then take the remainder.
def hash_sum(key, size):
total = 0
for ch in str(key):
total += ord(ch)
return total % size
# 1 1 (an anagram collides)
print(hash_sum("Amy", 7), hash_sum("Mya", 7))
- Simple and fast.
- Weakness: anagrams ("Amy", "Mya") always collide, and short keys use only a small range of totals, clustering in a few buckets.
Algorithm 2: weighted (polynomial) hash
Multiply by a constant before adding each character, so position matters:
def hash_poly(key, size):
h = 0
for ch in str(key):
h = (h * 31 + ord(ch)) % size
return h
# 4 5 (anagrams differ)
print(hash_poly("Amy", 7), hash_poly("Mya", 7))
- "Amy" and "Mya" no longer collide.
- The multiplier (often 31 or 33, a prime) mixes up the positions.
- Taking
% sizeat each step keeps the numbers small.
Algorithm 3: numeric keys
For integer keys (IDs, phone numbers):
def hash_mod(number, size):
return number % size
print(hash_mod(1234567, 11)) # 4
- Simple and quick, but poor if keys follow a pattern (for example all multiples of 10 with a table size of 10 would land in bucket 0).
- A prime size helps.
Other methods (for interest): mid-square (square the key and take the middle digits), folding (split a long key into pieces and add them).
Comparing the algorithms on a set of keys
Table size 7, keys ["Amy", "Mya", "Sam", "Raj", "Li", "Zoe"]:
| Key | Sum of codes mod 7 | Polynomial mod 7 |
|---|---|---|
| Amy | 1 | 4 |
| Mya | 1 | 5 |
| Sam | 2 | 6 |
| Raj | 5 | 1 |
| Li | 6 | 4 |
| Zoe | 1 | 5 |
- Sum of codes: bucket 1 gets three keys (Amy, Mya, Zoe), and buckets 0, 3 and 4 are empty.
- Polynomial: no bucket has more than two keys (Amy and Li share 4, Mya and Zoe share 5), so the longest chain is 2 instead of 3: a better spread. (With only 6 keys and 7 buckets, some collisions are hard to avoid.)
keys = ["Amy", "Mya", "Sam", "Raj", "Li", "Zoe"]
for fn in (hash_sum, hash_poly):
buckets = [0] * 7
for k in keys:
buckets[fn(k, 7)] += 1
print(fn.__name__, buckets)
# hash_sum [0, 3, 1, 0, 0, 1, 1]
# hash_poly [0, 1, 0, 0, 2, 2, 1]
Measuring quality: count how many keys land in each bucket, and the longest chain. An even spread means faster look-ups.
Python's own hash()
# an integer based on the value
print(hash(42), hash((1, 2)))
- Only immutable objects can be hashed (numbers, strings, tuples): a list is unhashable, which is why a dictionary key can't be a list.
- String hashes change from run to run (a security feature), so don't store them.
Hashing for other purposes
A cryptographic hash (SHA-256, 16.1.1) is a much stronger algorithm with fixed-length output, but slower and not used for hash-table indexes.
Worked example
Task: a library stores books by ISBN-like codes such as "BK4821" in a hash table of 11 buckets. Write a suitable hash algorithm and find the bucket for "BK4821".
def hash_code(code, size=11):
h = 0
for ch in code:
h = (h * 31 + ord(ch)) % size
return h
print(hash_code("BK4821")) # 0
Trace ( starts at 0; B=66, K=75, 4=52, 8=56, 2=50, 1=49):
| Character | Code | |
|---|---|---|
| B | 66 | |
| K | 75 | |
| 4 | 52 | |
| 8 | 56 | |
| 2 | 50 | |
| 1 | 49 |
So the result is 0. Check by running the code. Why it suits the keys: it uses every character with a weighting, so similar codes (BK4821, BK4812) go to different buckets, and the prime size 11 helps the spread.
Exam tip: always finish with % size so the index is valid. A good algorithm uses all of the key and gives an even spread. Say what is wrong with a poor one (anagrams collide, patterns cluster). Trace the calculation step by step, and check it by running it.
Check yourself
Why is the hash value taken modulo the table size?
To make sure it is a valid index between 0 and size − 1.
What is the weakness of adding up character codes?
Anagrams give the same hash, and short keys cluster in a small range, causing collisions.
Why does the polynomial hash multiply by a constant?
So that the position of each character affects the result, which spreads similar keys more evenly.
Why can't a list be used as a dictionary key?
Lists are mutable, so they can't be hashed; only immutable objects can.