Python 3D Academyবাংলা

The hash function: from a key to a bucket

🌍 In real life. At a post office, the sorter doesn't keep one big heap of letters. A wall of numbered pigeonholes stands behind the counter. For each letter the sorter reads one thing, the postcode, works out a pigeonhole number from it, and drops the letter there. Later, to find a letter for postcode 1205, nobody searches the whole wall: they go straight to that one pigeonhole.

A Python dict and set work exactly like that wall. This chapter opens the wall up and builds one.

The idea in one sentence: a hash function turns a key into a number, and that number, divided by the number of buckets, leaves a remainder that says which bucket the key lives in.

Its words:

  • key: what you look things up by (a word, a number, a postcode)
  • hash function: a rule that turns a key into a whole number, the same number every time
  • bucket: one pigeonhole of the table; a hash table is the row of buckets
  • collision: two different keys that land in the same bucket

How it works, step by step (a simple hash we can see: add up the letter codes):

  1. "cat" → ord("c") + ord("a") + ord("t") = 99 + 97 + 116 = 312
  2. with 4 buckets, 312 % 4 = 0, so "cat" goes into bucket 0
  3. to find "cat" later, do the same sum again: bucket 0, and look only there

Watch five animal names go in. "god" has the same letters as "dog", so the same sum: they collide and share a bucket.

Why it is correct. A hash function must give the same number for the same key, every time. Then put and find always agree on the bucket, just as the sorter and the postman both read the same postcode. Different keys may share a bucket (a collision); that only means the bucket holds a short list, which is searched.

What it costs. Working out the bucket costs a few steps for a short key (one addition per letter), then you look in one bucket. With n keys spread over enough buckets, each bucket holds about one key, so a lookup is about the same work for 10 keys or 10 million: O(1) on average.

Python's own hash. Python's hash() mixes the bits much better than our sum, so "dog" and "god" get different hashes. For safety, the hash of a string changes every time Python starts (so attackers can't plan collisions), but it stays the same while your program runs. Small whole numbers hash to themselves (all but -1, whose hash is -2).

def bucket(key, size):
    return sum(ord(c) for c in key) % size

for word in ["cat", "cow", "dog", "ant", "god"]:
    print(word, sum(ord(c) for c in word), bucket(word, 4))

print(hash(42), hash(-7))          # a whole number hashes to itself
print(hash("dog") == hash("dog"))  # the same key, the same hash

Mistakes and edge cases. A key must never change, or its bucket would change under it. That is why only immutable values can be dict keys or set items: a list key raises TypeError: unhashable type: 'list'. Use a tuple instead: (2, 3) works, [2, 3] doesn't.

seats = {}
seats[(2, 3)] = "Mina"     # a tuple key: fine
print(seats)
seats[[4, 1]] = "Rafi"     # a list key: TypeError
Lists can change, so Python refuses to hash them.

Quiz

  1. With our letter-sum hash and 4 buckets, which bucket does "ab" go into? (ord("a") is 97, ord("b") is 98.)

    print(sum(ord(c) for c in "ab") % 4)
  2. What must a hash function always do?

    • Give the same number for the same key
    • Give a different number for every key, with no collisions
    • Sort the keys
  3. Why do "listen" and "silent" always collide with the letter-sum hash?

    • They have the same letters, so the same sum
    • They are the same length
    • They start with different letters
  4. What does this print?

    print(hash(10) % 4, hash(13) % 4)
  5. Which line raises an error?

    visited = set()
    visited.add((0, 0))
    visited.add([1, 0])
    print(len(visited))

Coding tasks

  1. Write bucket(key, size): the sum of the letter codes of key, taken modulo size.

  2. Write spread(keys, size): a list of size buckets (lists), each key placed in the bucket the letter-sum hash gives it, in the order the keys come.