尝试添加插入(自键,键)方法,将线键插入到适当的位置,同时线性探测以解决冲突。 我目前的代码,我只是不确定如何将str插入哈希表。
测试代码:
#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
我只需要一些关于如何将字符串添加到哈希表中的建议。
答案 0 :(得分:2)
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
更新 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