Created
August 3, 2021 04:55
-
-
Save Edald123/43dfd10b0a3d912f7d1dc5979119a061 to your computer and use it in GitHub Desktop.
Hash map using separate chaining to avoid collisions in Python
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_for_hash import Node, LinkedList | |
from blossom_lib import flower_definitions | |
class HashMap: | |
def __init__(self, size): | |
self.array_size = size | |
self.array = [LinkedList() for i in range(size)] | |
def hash(self, key): | |
return sum(key.encode()) | |
def compress(self, hash_code): | |
return hash_code % self.array_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] | |
return None | |
blossom = HashMap(len(flower_definitions)) | |
for flower in flower_definitions: | |
blossom.assign(flower[0], flower[1]) | |
print(blossom.retrieve('daisy')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment