Edexcel International Advanced Level Computer Science, point 18.2.3
The hash table was explained in 14.1.2. Here you write one in code, represented with classes or references, and handle it with calculate hash value, insert, remove, find and traverse. Collision handling is in 18.2.5, and the hash algorithm in 18.2.4. Check the PLS for exact method names.
a. Represent
With classes
A class holds the table (a list of buckets), its size and a count, and its methods.
class HashTable:
def __init__(self, size=7):
self.size = size
# each bucket is a list
self.buckets = [[] for _ in range(size)]
self.count = 0
Each bucket is a list of (key, value) pairs (separate chaining), so that several items can share a bucket.
With references
The same structure using only lists (no class): a list of buckets, each bucket a list of [key, value] pairs.
size = 7
# table[i] is the bucket at index i
table = [[] for _ in range(size)]
With linked lists: each bucket holds the head of a linked list (a reference), as in 18.2.2.
b. Handle
Calculate hash value
def hash_value(self, key):
total = 0
for ch in str(key):
total = total + ord(ch)
return total % self.size
Deterministic, always between 0 and size - 1 (18.2.4).
Insert
Hash the key, find the bucket, update if the key exists, otherwise add.
def insert(self, key, value):
bucket = self.buckets[self.hash_value(key)]
for pair in bucket:
if pair[0] == key:
pair[1] = value # key exists: update it
return
bucket.append([key, value])
self.count += 1
Find
def find(self, key):
bucket = self.buckets[self.hash_value(key)]
for k, v in bucket:
if k == key:
return v
return None # not found
Remove
def remove(self, key):
bucket = self.buckets[self.hash_value(key)]
for i, (k, v) in enumerate(bucket):
if k == key:
del bucket[i]
self.count -= 1
return True
return False
Traverse
def traverse(self):
for index, bucket in enumerate(self.buckets):
for k, v in bucket:
yield index, k, v
yield makes a generator: it hands back one item at a time. (Or build and return a list.)
Test and trace
ht = HashTable(7)
ht.insert("Amy", 17)
ht.insert("Sam", 18)
ht.insert("Mya", 16) # collides with Amy (both hash to 1)
print(ht.find("Amy"), ht.find("Mya"), ht.find("Zed")) # 17 16 None
ht.insert("Amy", 19) # updates
print(ht.find("Amy"), ht.count) # 19 3
print(ht.remove("Sam"), ht.remove("Sam")) # True False
for index, k, v in ht.traverse():
print(index, k, v)
Hash values (sum of character codes mod 7): Amy = 295 mod 7 = 1, Sam = 289 mod 7 = 2, Mya = 295 mod 7 = 1 (a collision: both go into bucket 1).
| Bucket | Contents |
|---|---|
| 0 | |
| 1 | [Amy, 19], [Mya, 16] |
| 2 | [Sam, 18] → removed |
| 3 to 6 |
Test cases: an empty table, a key not present, a key that updates, two keys that collide, removing a key that isn't there.
Load factor
def load_factor(self):
return self.count / self.size
For 3 items in 7 buckets, it is . Rehash when it passes a limit (about 0.7, 18.2.5).
Hash table or dictionary?
Python's dict is already a hash table, so in real programs use it. Writing one by hand shows how it works, and is what the exam asks.
Worked example
Task: use the hash table to count how many times each word occurs.
words = "the cat and the dog and the bird".split()
counts = HashTable(7)
for w in words:
current = counts.find(w)
counts.insert(w, 1 if current is None else current + 1)
for index, word, n in counts.traverse():
print(word, n)
# 3 2 None
print(counts.find("the"), counts.find("and"), counts.find("cow"))
the occurs 3 times, and twice, and cat, dog, bird once each, found in about one step each whatever the number of words. The order of the output follows the buckets, not the order of the words.
Exam tip: always compute the bucket index first (hash % size), then handle the cases: empty bucket, key already there (update), collision (add to the chain). Show the table after each insert. State the load factor if asked.
Check yourself
What does the insert method do if the key already exists?
It updates the existing value instead of adding a duplicate.
Why is the hash value taken mod the table size?
So that the index is always a valid position in the table (0 to size − 1).
What does find return when the key isn't present?
None (or another value that means not found).
How is the load factor calculated?
The number of items stored divided by the number of buckets.