Skip to content

Instantly share code, notes, and snippets.

@lub0s
Created May 14, 2024 11:15
Show Gist options
  • Save lub0s/08b8b23441ac563950a77a1cd76d4525 to your computer and use it in GitHub Desktop.
Save lub0s/08b8b23441ac563950a77a1cd76d4525 to your computer and use it in GitHub Desktop.
class HashMap:
def __init__(self, size):
self.hashmap = [None for i in range(size)]
def insert(self, key, value):
self.resize()
index = self.key_to_index(key)
self.hashmap[index] = (key, value)
def resize(self):
old_len = len(self.hashmap)
if old_len == 0:
self.hashmap = [None]
return
load = self.current_load()
if load >= 0.05:
old_map = self.hashmap
self.hashmap = [None for i in range(10 * len(self.hashmap))]
for kv in old_map:
if kv is not None: self.insert(kv[0], kv[1])
def current_load(self):
l = len(self.hashmap)
if l == 1: return 1
not_nones = 0
for i in self.hashmap:
if i is not None: not_nones += 1
return not_nones / l
def key_to_index(self, key):
sum = 0
for c in key:
sum += ord(c)
return sum % len(self.hashmap)
def __repr__(self):
final = ""
for i, v in enumerate(self.hashmap):
if v != None:
final += f" - {str(v)}\n"
return final
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment