hash_map.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. class Item(object):
  2. def __init__(self, key, value):
  3. self.key = key
  4. self.value = value
  5. class HashTable(object):
  6. def __init__(self, size):
  7. self.size = size
  8. self.table = [[] for _ in range(self.size)]
  9. def _hash_function(self, key):
  10. return key % self.size
  11. def set(self, key, value):
  12. hash_index = self._hash_function(key)
  13. for item in self.table[hash_index]:
  14. if item.key == key:
  15. item.value = value
  16. return
  17. self.table[hash_index].append(Item(key, value))
  18. def get(self, key):
  19. hash_index = self._hash_function(key)
  20. for item in self.table[hash_index]:
  21. if item.key == key:
  22. return item.value
  23. raise KeyError('Key not found')
  24. def remove(self, key):
  25. hash_index = self._hash_function(key)
  26. for index, item in enumerate(self.table[hash_index]):
  27. if item.key == key:
  28. del self.table[hash_index][index]
  29. return
  30. raise KeyError('Key not found')