2015-02-10 99 views
0

我一直在爲我的MyChainHashTable類嘗試編寫insert(self, key)方法。鏈式哈希表:插入功能

它應該使用單獨的鏈接來處理衝突解決。如果密鑰不在散列表中,那麼它應該在密鑰鏈接列表的末尾插入密鑰並返回hashkey。如果密鑰已經在哈希表中,那麼它應該返回-1

這裏是我的類:

class MyChainHashTable: 

    def __init__(self, capacity): 
     self.capacity = capacity 
     self.slots = [ ] 
     for i in range(self.capacity): 
      self.slots.append([]) 

    def __str__(self): 
     info = "" 
     for items in self.slots: 
      info += str(items) 
     return info 

    def __len__(self): 
     count = 0 
     for i in self.slots: 
      count += len(i) 
     return count 

    def hash_function(self, key): 
     i = key % self.capacity 
     return i 

我嘗試這樣做:

def insert(self, key): 
     self.slots[self.hash_function(key)].append(key) 

但我不知道如何解決衝突或如何返回-1

測試是:

x = MyChainHashTable(2) 
print("Add 3, return:", x.insert(3)) 
print("Add 3, return:", x.insert(3)) 
print("Hashtable:", x) 

的結果應該是:

Add 3, return: 1 
Add 3, return: -1 
Hashtable: [][3] 

回答

1

這確實你說你想要的:

def insert(self, key): 
     slot = self.hash_function(key) 
     if key in self.slots[slot]: 
      return -1 
     else: 
      self.slots[slot].append(key) 
      return slot