Hash Table Open Addressing Double Hash (Python)

Implement a hash table with open addressing and double hashing for collision resolution in Python.

PythonData Integrity

Code

pythonsnippet
39 lines
class HashTable:
    def __init__(self, size=101):
        self.size = size
        self.keys = [None] * size
        self.vals = [None] * size

    def _h1(self, key):
        h = 0
        for c in str(key):
            h = (h * 31 + ord(c)) % self.size
        return h

    def _h2(self, key):
        h = 0
        for c in str(key):
            h = (h * 17 + ord(c)) % (self.size - 1)
        return h + 1

    def set(self, key, val):
        step = self._h2(key)
        idx = self._h1(key)
        for _ in range(self.size):
            if self.keys[idx] is None or self.keys[idx] == key:
                self.keys[idx] = key
                self.vals[idx] = val
                return
            idx = (idx + step) % self.size
        raise OverflowError("table full")

    def get(self, key):
        step = self._h2(key)
        idx = self._h1(key)
        for _ in range(self.size):
            if self.keys[idx] is None:
                return None
            if self.keys[idx] == key:
                return self.vals[idx]
            idx = (idx + step) % self.size
        return None

What the code does

Count the class HashTable and the functions __init__, _h1, _h2 and set as the entire surface area of Hash Table Open Addressing Double Hash (Python).

The one repetition in this snippet is the loop for c in str(key). The OverflowError throw is the give-up path: it fires only after the loop above it has gone through every attempt without the early return firing.

Applying it

Signature: def set(self, key, val)

set is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

if self.keys[idx] is None or self.keys[idx] == key:
    self.keys[idx] = key
    self.vals[idx] = val
    return
def __init__(self, size=101):
    self.size = size
    self.keys = [None] * size
    self.vals = [None] * size
if self.keys[idx] is None:
    return None

Interactive Tools for This Topic

FAQ

When does the loop stop?
When every attempt is spent: the throw sits behind the loop, so it happens only after the last attempt fails to exit early.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `__init__`, `_h1`, `_h2` at load time.