-
-
Save codecademydev/ff5e154482a93363d5277b2166448251 to your computer and use it in GitHub Desktop.
Codecademy export
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from linked_list import Node, LinkedList | |
from blossom_lib import flower_definitions | |
class HashMap: | |
def __init__(self, size): | |
self.size = size | |
self.array = [LinkedList() for i in range(self.size)] | |
def hash(self, key): | |
return sum(key.encode()) | |
def compress(self, hash_code): | |
return hash_code % self.size | |
def assign(self, key, value): | |
hash_code = self.hash(key) | |
array_index = self.compress(hash_code) | |
payload = Node([key, value]) | |
list_at_array = self.array[array_index] | |
for item in list_at_array: | |
if item[0] == key: | |
item[1] = value | |
list_at_array.insert(payload) | |
def retrieve(self, key): | |
hash_code = self.hash(key) | |
array_index = self.compress(hash_code) | |
list_at_index = self.array[array_index] | |
for item in list_at_index: | |
if item[0] == key: | |
return item[1] | |
else: | |
return None | |
blossom = HashMap(len(flower_definitions) + 1) | |
for flower in flower_definitions: | |
blossom.assign(flower[0], flower[1]) | |
blossom.assign("pansy", "some nonsense") | |
print(blossom.retrieve("daisy")) | |
print(blossom.retrieve("sunflower")) | |
print(blossom.retrieve("pansy")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment