Facebook
From Unique Lion, 2 Months ago, written in Python.
Embed
Download Paste or View Raw
Hits: 46
  1. class HashTable:
  2.     def __init__(self):
  3.         self.size = 11
  4.         self.slots = [None] * self.size
  5.         self.data = [None] * self.size
  6.  
  7.     def put(self, key, data):
  8.         hash_value = self.hash_function(key, len(self.slots))
  9.  
  10.         if self.slots[hash_value] is None:
  11.             self.slots[hash_value] = key
  12.             self.data[hash_value] = data
  13.         else:
  14.             if self.slots[hash_value] == key:
  15.                 self.data[hash_value] = data # Replace.
  16.             else:
  17.                 next_slot = self.rehash_function(hash_value, len(self.slots))
  18.  
  19.                 while self.slots[next_slot] is not None and self.slots[next_slot] != key:
  20.                     next_slot = self.rehash_function(next_slot, len(self.slots))
  21.  
  22.                 if self.slots[next_slot] is None:
  23.                     self.slots[next_slot] = key
  24.                     self.data[next_slot] = data
  25.                 else:
  26.                     self.data[next_slot] = data # Replace.
  27.  
  28.     def get(self, key):
  29.         start_slot = self.hash_function(key, len(self.slots))
  30.  
  31.         data = None
  32.         stop = False
  33.         found = False
  34.         position = start_slot
  35.  
  36.         while self.slots[position] is not None and not found and not stop:
  37.             if self.slots[position] == key:
  38.                 found = True
  39.                 data = self.data[position]
  40.             else:
  41.                 print(stop)
  42.                 position = self.rehash_function(position, len(self.slots)) # Increases index by 1 everytime.
  43.                 # For example: Key 54's hash is 10, 54 + 1 % 11 = 0. It means it starts from zero through list in
  44.                 # this case.
  45.  
  46.                 if position == start_slot:
  47.                     stop = True
  48.  
  49.         return data
  50.  
  51.     @staticmethod
  52.     def hash_function(key, size):
  53.         return key % size
  54.  
  55.     @staticmethod
  56.     def rehash_function(oldhash, size):
  57.         return (oldhash + 1) % size
  58.  
  59.  
  60. hashtable1 = HashTable()
  61. hashtable1.put(54, 'cat')
  62. print(hashtable1.get(54))