fork download
  1. class HashTable:
  2. def __init__(self):
  3. self.size = 11
  4. self.capacity = self.size
  5. self.slots = [None] * self.size
  6. self.data = [None] * self.size
  7.  
  8. def hashfunction(self, key, size):
  9. return key%size
  10.  
  11. def rehash(self, oldhash, size):
  12. return (oldhash+1)%size
  13.  
  14. def put(self, key, value):
  15. hashvalue = self.hashfunction(key,len(self.slots))
  16.  
  17. if self.capacity < 1:
  18. self.slots += [None]
  19. self.data += [None]
  20. self.capacity += 1
  21.  
  22. if self.slots[hashvalue] == None:
  23. self.slots[hashvalue] = key
  24. self.data[hashvalue] = value
  25. self.capacity -= 1
  26. else:
  27. if self.slots[hashvalue] == key:
  28. self.data[hashvalue] = data
  29. else:
  30. rehashed = self.rehash(hashvalue, len(self.slots))
  31. while self.slots[rehashed] != None and self.slots[rehashed] != key:
  32. rehashed = self.rehash(rehashed, len(self.slots))
  33. if self.slots[rehashed] == None:
  34. self.slots[rehashed] = key
  35. self.data[rehashed] = value
  36. self.capacity -= 1
  37. else:
  38. self.data[rehashed] = value
  39.  
  40. def get(self, key):
  41. startslot = self.hashfunction(key, len(self.slots))
  42. data = None
  43. found = False
  44. stop = False
  45. position = startslot
  46. while self.slots[position] != None and not found and not stop:
  47. if self.slots[position] == key:
  48. data = self.data[key]
  49. found = True
  50. else:
  51. position = self.rehash(position, len(self.slots))
  52. if position == startslot:
  53. stop = True
  54. return data
  55.  
  56. def __delitem__(self, key):
  57. hashvalue = self.hashfunction(key, len(self.slots))
  58.  
  59. if self.slots[hashvalue] == key:
  60. self.slots[hashvalue] = None
  61. self.data[hashvalue] = None
  62. else:
  63. rehashed = self.hashfunction(hashvalue, len(self.slots))
  64. while self.slots[rehashed] != key:
  65. rehashed = self.hashfunction(rehashed, len(self.slots))
  66. if self.slots[rehashed] == key:
  67. self.slots[rehashed] == None
  68. self.data[rehashed] == None
  69.  
  70. def __contains__(self, key):
  71. return key in self.slots
  72.  
  73. def __getitem__(self, key):
  74. return self.get(key)
  75.  
  76. def __setitem__(self, key, value):
  77. self.put(key, value)
  78.  
  79. h = HashTable()
  80. h[0] = 5
  81. h[11] = 6
  82. del h[0]
  83. print(h[11])
Success #stdin #stdout 0s 23304KB
stdin
Standard input is empty
stdout
None