Hash Table Open Addressing Double Hash (Python)
Implement a hash table with open addressing and double hashing for collision resolution in Python.
Code
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 NoneWhat 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
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.