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 != None: bucket = bucket bucket = [key, value, None] def get(self, key): address = self._hash(key) bucket = self.data[address] if bucket: while bucket != None or key != bucket: bucket = bucket if bucket: return bucket raise KeyError def keys(self): keys_list =  bucket_list = self.data for bucket in bucket_list: current_bucket = bucket if bucket: while current_bucket != None: keys_list.append(current_bucket) current_bucket = current_bucket return keys_list
%with anything other than the size is usually wrong. And
> bucket_length - 1? What about
>= bucket_length? What's so special about