Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Design generic hashMap with iterator
- get(ele)
- put(ele, val)
- """
- class HashMap:
- def __init__(self, n):
- self.cache = [[]] * n # each value is list
- self.n = n
- def __calculateHash(self, val) -> int:
- return hash(val) % self.n
- def get(self, ele):
- index = self.__calculateHash(ele)
- for k, v in self.cache[index]:
- if k == key:
- return v
- return None
- def put(self, key, val):
- index = self.__calculateHash(key)
- # Overwrite the value if the key already exists
- for i, (k, _) in enumerate(self.cache[index]):
- if k == key:
- self.cache[index][i] = (key, val)
- return
- # If the key is new, append it to the list at the calculated index
- self.cache[index].append((key, val))
- def __iter__(self):
- for bucket in self.cache:
- for key, value in bucket:
- yield key, value
- # Testing
- map = HashMap(10)
- map.put("one", 30)
- map.put("two", 31)
- map.put(3, 40)
- for k, v in map:
- print(k, v)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement