Advertisement
nirajs

hash map design

Jan 1st, 2024
809
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. """
  2. Design generic hashMap with iterator
  3.    get(ele)
  4.    put(ele, val)
  5. """
  6.  
  7. class HashMap:
  8.  
  9.     def __init__(self, n):
  10.         self.cache = [[]] * n # each value is list
  11.         self.n = n
  12.  
  13.     def __calculateHash(self, val) -> int:
  14.         return hash(val) % self.n
  15.  
  16.     def get(self, ele):
  17.         index = self.__calculateHash(ele)
  18.         for k, v in self.cache[index]:
  19.             if k == key:
  20.                 return v
  21.         return None
  22.  
  23.     def put(self, key, val):
  24.         index = self.__calculateHash(key)
  25.         # Overwrite the value if the key already exists
  26.         for i, (k, _) in enumerate(self.cache[index]):
  27.             if k == key:
  28.                 self.cache[index][i] = (key, val)
  29.                 return
  30.         # If the key is new, append it to the list at the calculated index
  31.         self.cache[index].append((key, val))
  32.  
  33.     def __iter__(self):
  34.         for bucket in self.cache:
  35.             for key, value in bucket:
  36.                 yield key, value
  37.  
  38. # Testing
  39. map = HashMap(10)
  40.  
  41. map.put("one", 30)
  42. map.put("two", 31)
  43. map.put(3, 40)
  44.  
  45. for k, v in map:
  46.     print(k, v)
  47.  
  48.  
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement