I attempted making a hashmap in python, and it was harder, due to some limitations but this is my version of dictionaries in python. Are there any way to simplify or do the same thing in less code along with tips and tricks?
class HashMap:
def __init__(self, memory): # refers to the length of the bucket
self.data = [None] * memory
self.memory = memory
def _hash(self, key):
hashed_value = 0
bucket_length = self.memory
string_length = len(key)
i = 0
while i < string_length:
hashed_value += (ord(key[i]) * i) % bucket_length
if hashed_value > bucket_length-1:
hashed_value %= bucket_length-1
i += 1
return hashed_value
def set(self, key, value):
address = self._hash(key)
bucket = self.data[address]
if not bucket:
self.data[address] = [key, value, None] # None refers to next pointer
else:
while bucket[2] != None:
bucket = bucket[2]
bucket[2] = [key, value, None]
def get(self, key):
address = self._hash(key)
bucket = self.data[address]
if bucket:
while bucket[2] != None or key != bucket[0]:
bucket = bucket[2]
if bucket:
return bucket[1]
raise KeyError