Skip to content

Instantly share code, notes, and snippets.

@say4n
Last active March 26, 2020 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save say4n/3ba64c8b33f94a3526941a4b4618430d to your computer and use it in GitHub Desktop.
Save say4n/3ba64c8b33f94a3526941a4b4618430d to your computer and use it in GitHub Desktop.
A very crude, inefficient HashMap implementation.
#! /usr/bin/env python3
import random
class HashMap:
def __init__(self, num_buckets=100):
self.num_buckets = num_buckets
self.buckets = [[] for _ in range(num_buckets)]
def put(self, key, val):
index = self._hash(key)
if len(self.buckets[index]) != 0:
self.buckets[index].append((key, val))
else:
self.buckets[index] = [(key, val)]
def get(self, key):
index = self._hash(key)
if len(self.buckets[index]) == 0:
raise KeyError(f"KeyError: {key} not found.")
else:
for k, val in self.buckets[index]:
if k == key:
return val
raise KeyError(f"KeyError: {key} not found.")
def _hash(self, key):
return key % self.num_buckets
def __repr__(self):
return f"{self.buckets}"
if __name__ == "__main__":
h = HashMap()
random.seed(42)
for _ in range(1000):
key, value = random.randint(1, 1000), random.randint(1, 1000)
h.put(key, value)
for _ in range(15):
key = random.randint(1, 1000)
try:
h.get(key)
except KeyError as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment