链散列表:插入函数

时间:2015-02-10 21:22:39

标签: python hash insert hashtable

我一直在尝试为insert(self, key)课程编写MyChainHashTable方法。

应该使用单独的链接来处理冲突解决。如果密钥不在哈希表中,那么它应该在哈希密钥链表的末尾插入密钥并返回哈希密钥。如果密钥已经在哈希表中,那么它应该返回-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 个答案:

答案 0 :(得分: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