Sub topic 6
Bad hashes: summing characters and other traps
This chapter assumes you know Python basics, bytes, and the modulo operator. You also need the earlier ideas that a hash function is deterministic and should spread keys evenly across buckets. Here you will see how a plausible-looking hash fails those goals.
The summing trap
An obvious way to hash a string is to add up its character codes. The result is deterministic and fast, and it is easy to write. Its flaw is that addition ignores order, so any rearrangement of the same letters gives the same value.
def sum_hash(s, buckets):
return sum(s.encode()) % buckets
def poly_hash(s, buckets, base=31):
h = 0
for b in s.encode():
h = (h * base + b) % (2**32)
return h % buckets
anagrams = ["listen", "silent", "enlist", "tinsel", "inlets"]
print([sum_hash(w, 16) for w in anagrams])
print([poly_hash(w, 16) for w in anagrams])The first line prints the same bucket five times, because the codes of these letters always add up to 655. The polynomial hash multiplies the running value by a base before adding each byte, so each position contributes differently. Its outputs differ across the five words.
Why the damage is bigger than it looks
Anagrams are only one failure. The sum also clusters. Short lowercase words produce sums in a narrow range, and many values in that range occur far more often than others. A table sized for thousands of buckets will leave most of them empty. This breaks the uniformity property from earlier in the tutorial. Lookups degrade from a constant number of steps toward a linear scan of one long bucket.
Other common traps
- Using only part of the key. Hashing just the first character or the length puts every key with a shared prefix or length in one bucket. File paths, URLs, and names all share long prefixes.
- Ignoring bucket structure. If a hash returns multiples of 16 (aligned IDs or addresses, for example) and the table has 16 buckets, then
h % 16is always 0. Power-of-two table sizes only use the low bits of the hash, so those bits must vary. - Non-determinism. A hash that depends on a random number, the current time, or a memory address will not find the key again on a later lookup. This breaks the core guarantee. Seeded hashes avoid the problem by fixing the seed for the lifetime of the table.
- Mutable keys. If a key changes after insertion, its hash changes and the entry is stranded in the wrong bucket. This is why Python refuses to hash a
list.
Testing a hash before you trust it
Do not judge a hash by reading it. Hash realistic data and count how many keys land in each bucket.
from collections import Counter
def first_char_hash(s, buckets):
return s.encode()[0] % buckets
paths = [f"/usr/lib/module{i}" for i in range(1000)]
counts = Counter(first_char_hash(p, 16) for p in paths)
print(counts)All 1000 paths land in one bucket, because they share the leading /. An even spread would put about 62 keys in each of the 16 buckets. Always test with data that looks like your real keys, not random strings.
Exercise
A table has 8 buckets, and the hash function returns the key's integer ID unchanged. Keys are 8, 16, 24, 32 and 40. Which buckets do they use, and what is the underlying problem?
Show answer
All five keys land in bucket 0, since each is a multiple of 8. The hash passes through structure in the input, and a power-of-two table size looks only at the low bits. A hash that mixes all bits, such as polynomial hashing or FNV-1a, avoids this.