Advertisement
GeorgiLukanov87

HashMap by Diyan

Dec 2nd, 2022
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.98 KB | None | 0 0
  1. class HashMap:
  2.     def __init__(self):
  3.         self.__max_capacity = 4
  4.         self.__keys = [None] * self.__max_capacity
  5.         self.__values = [None] * self.__max_capacity
  6.  
  7.     def get(self, key, default=None):
  8.         try:
  9.             index = self.__keys.index(key)
  10.             return self.__values[index]
  11.         except ValueError:
  12.             return default
  13.  
  14.     def add(self, key, value):
  15.         self[key] = value
  16.  
  17.     def size(self):
  18.         return len([el for el in self.__keys if el is not None])
  19.  
  20.     def __getitem__(self, key):
  21.         try:
  22.             index = self.__keys.index(key)
  23.             return self.__values[index]
  24.         except ValueError:
  25.             raise KeyError(key)
  26.  
  27.     def __setitem__(self, key, value):
  28.         if key in self.__keys:
  29.             index = self.__keys.index(key)
  30.             self.__values[index] = value
  31.             return
  32.  
  33.         if self.__max_capacity == self.size():
  34.             self.__resize()
  35.  
  36.         index = self.__calc_index(key)
  37.         index = self.__free_index(index)
  38.  
  39.         self.__keys[index] = key
  40.         self.__values[index] = value
  41.  
  42.     def __len__(self):
  43.         return self.__max_capacity
  44.  
  45.     def __str__(self):
  46.         key_value_pairs = []
  47.  
  48.         for i in range(len(self.__keys)):
  49.             if self.__keys[i] is not None:
  50.                 key_value_pairs.append(f"{self.__keys[i]}: {self.__values[i]}")
  51.  
  52.         return "{" + ', '.join(key_value_pairs) + "}"
  53.  
  54.     def __calc_index(self, key):
  55.         return sum([ord(char) for char in str(key)]) % self.__max_capacity
  56.  
  57.     def __free_index(self, index):
  58.         if index == self.__max_capacity:
  59.             index = 0
  60.  
  61.         if self.__keys[index] is None:
  62.             return index
  63.  
  64.         return self.__free_index(index + 1)
  65.  
  66.     def __resize(self):
  67.         self.__keys = self.__keys + [None] * self.__max_capacity
  68.         self.__values = self.__values + [None] * self.__max_capacity
  69.         self.__max_capacity *= 2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement