https://www.codecademy.com/paths/computer-science/tracks/cspath-cs-102/modules/hash-maps/projects/blossom
Hello, I am newbie, first time leaner here. I have questions for this exercise and hope they’re not too silly.
This is the final code:
from linked_list import Node, LinkedList
class HashMap:
def __init__(self,size):
self.array_size = size
self.array = [LinkedList() for i in range(size)]
def hash(self,key):
hash_code = sum(key.encode())
return hash_code
def compress(self,hash_code):
return hash_code % self.array_size
def assign(self,key,value):
array_index = self.compress(self.hash(key))
payload = Node([key,value])
list_at_array = self.array[array_index]
for item in list_at_array:
if key == item[0]:
item[1] = value
return
list_at_array.insert(payload)
def retrieve(self,key):
array_index = self.compress(self.hash(key))
list_at_index = self.array[array_index]
for item in list_at_index:
if item[0] == key:
return item[1]
else:
return None
So first, since each index of the array is a Linked List, how is it possible to iterate through the Linked List by this?
list_at_array = self.array[array_index]
for item in list_at_array:
And secondly, why don’t we insert the new [key,value] directly to self.array[array_index] but instead insert them through an instance variable list_at_array. Doesn’t it only assign the new [key,value] to the instance variable, and not the array index it self?
I mean the code works perfectly fine. But I just don’t get it.
def assign(self,key,value):
array_index = self.compress(self.hash(key))
payload = Node([key,value])
list_at_array = self.array[array_index]
for item in list_at_array:
if key == item[0]:
item[1] = value
return
list_at_array.insert(payload)
So much thanks in advance.