gpt4 book ai didi

python - 将字符串添加到哈希表中

转载 作者:行者123 更新时间:2023-12-01 03:57:40 25 4
gpt4 key购买 nike

尝试添加一个 insert(self, key) 方法,在线性探测解决冲突时将键插入适当的位置。我当前的代码,我只是不能 100% 确定如何将 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

我只需要一些关于如何将字符串添加到哈希表中的建议。

最佳答案

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

关于python - 将字符串添加到哈希表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37156829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com