This is a simple implementation of a Map using a simple Hashing Function and an Array (of fixed size) as Storage
- Key Type: String
- Value Type: Any
- No Hash Collision Management yet, just Hash Collision Detection
# Specs for Naive Hashing | |
# - Input: String | |
# - Output: Array id | |
# - Naive Hashing Function: sum all the string letters and mod for array size to get an id | |
def hash_str(in_str, in_lin_storage_size): | |
full_hash_val=0 | |
if(type(in_str) is not str): | |
raise(ValueError("Arg1 needs to be string")) | |
for c in in_str: | |
#print("Char " + str(c)) | |
full_hash_val += ord(c) | |
final_hash_val = full_hash_val % in_lin_storage_size | |
#print("Full Hash is " + str(full_hash_val) + ", Final Hash Val is " + str(final_hash_val)) | |
return final_hash_val | |
class MyMap: | |
def __init__(self, size): | |
self.__storage__ = [None] * size | |
def size(self): | |
return len(self.__storage__) | |
def insert(self, key, value): | |
h = hash_str(key, len(self.__storage__)) | |
if(self.__storage__[h] is not None): | |
raise(ValueError("Collision Detected")) | |
else: | |
self.__storage__[h] = value | |
def get(self, key): | |
h = hash_str(key, len(self.__storage__)) | |
return self.__storage__[h] | |
# Print Your code here | |
hash_str("ciao bello", 100) | |
a = MyMap(5) | |
print("a.size=" + str(a.size())) | |
a.insert("ciao", 5) | |
a.insert("test", 11) | |
print("a['ciao'] = " + str(a.get("ciao"))) | |
print("a['test'] = " + str(a.get("test"))) | |
print("a['what'] = " + str(a.get("what"))) | |