Python哈希与列表

时间:2014-10-10 03:50:02

标签: python hash

我需要一些帮助来创建一个insert函数,它将值添加到哈希表中,其中每个表位置都是一个列表。如果存在冲突,则将值添加到正确位置的列表中。

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):
        #need help 
        #this should insert each value into seperate lists, and if there is collision
        #it should add the value to make a list with +1 positions. 
        #eg. [26][][54, 93][][17, 43][31][][][][][][][77, 90]  

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以使用字典:

def insertWithChain(dict, key, value):
    if key in d:
        d[key].append(value) # add value to an existing list
    else:
        d[key] = [value] # new value in a new list by itself