将字符串添加到哈希 table

adding a string into hash table

尝试添加一个 insert(self, key) 方法,在线性探测解决冲突时将密钥插入适当的位置。 我当前的代码,我只是不是 100% 确定如何将 str 插入哈希 table。

测试代码:

#Test
my_table  = HashTable(5)
my_table.insert('hello')
print("Hashtable:", my_table)   

结果:

Hashtable: [None, None, None, None, 'hello']

class HashTable:

    def __init__(self, capacity): 
        self.capacity = capacity 
        self.slots = [None] * self.capacity

    def __str__(self): 
        return str(self.slots )

    def is_empty(self): 
        return self.slots.count(None) == len(self.slots)

    def hash(self, key):
        sum = 0
        for char in key: 
            sum += ord(char) 
            sum2 = "%04d" % (sum) 
            digits = int((sum2[2]) + (sum2[3])) 
            number = int(digits * digits) 
        return number % len(self.slots)


    def insert(self, key): 
        count = 0 
        position = key%self.capacity 
        if self.slots[key%self.capacity] == None: 
            self.slots[key%self.capacity] = key 
        else: 
            while self.slots[position] != None: 
                position +=1 
                if position >= self.capacity: 
                    position = 0 
            self.slots[position%self.capacity] = key 
            return self.slots

我目前遇到类型错误

>>>TypeError: not all arguments converted during string formatting line 25, in insert
    position = key%self.capacity

我只需要一些关于如何将字符串添加到散列中的建议 table。

key ('hello') 是一个字符串对象。您需要将其转换为整数才能进行取模。否则它将执行 printf-style string formatting;导致错误,因为字符串中没有 %

position = key % self.capacity

调用self.hash获取哈希值:

def insert(self, key): 
    position = self.hash(key) % self.capacity 
    if self.slots[position] == None: 
        self.slots[position] = key 
    else: 
        while self.slots[position] != None:
            position += 1
            if position >= self.capacity: 
                position = 0
        self.slots[position%self.capacity] = key
        return self.slots

UPDATE if 正文可以合并到 else:

def insert(self, key): 
    position = self.hash(key) % self.capacity
    while self.slots[position] != None:
        position += 1
        if position >= self.capacity:
            position = 0
    self.slots[position%self.capacity] = key
    return self.slots