03-HT-Get.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. class HashTable:
  2. def __init__(self, size = 7):
  3. self.data_map = [None] * size
  4. def __hash(self, key):
  5. my_hash = 0
  6. for letter in key:
  7. my_hash = (my_hash + ord(letter) * 23) % len(self.data_map)
  8. return my_hash
  9. def print_table(self):
  10. for i, val in enumerate(self.data_map):
  11. print(i, ": ", val)
  12. def set_item(self, key, value):
  13. index = self.__hash(key)
  14. if self.data_map[index] == None:
  15. self.data_map[index] = []
  16. self.data_map[index].append([key, value])
  17. def get_item(self, key):
  18. index = self.__hash(key)
  19. if self.data_map[index] is not None:
  20. for i in range(len(self.data_map[index])):
  21. if self.data_map[index][i][0] == key:
  22. return self.data_map[index][i][1]
  23. return None
  24. my_hash_table = HashTable()
  25. my_hash_table.set_item('bolts', 1400)
  26. my_hash_table.set_item('washers', 50)
  27. print(my_hash_table.get_item('bolts'))
  28. print(my_hash_table.get_item('washers'))
  29. print(my_hash_table.get_item('lumber'))