我正试图用以下代码创建哈希表,但当我创建它的实例时,会得到一个:
TypeError: not all arguments converted during string formatting
我不太确定哪里出错了;类型错误似乎是在我使用函数hashfunction
时出现的,但我似乎看不到类型错误在哪里。你知道吗
class HashTable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def hashfunction(self, key, size):
# key is already the hashed ID
return key % size
def rehash(self, old_hash_value, size):
return (old_hash_value + 1) % size
def put(self, key, data):
hashvalue = self.hashfunction(data, len(self.slots))
if self.slots[hashvalue] == None:
self.slots[hashvalue] = hashvalue
self.data[hashvalue] = data
else:
if self.slots[hashvalue] == key:
self.data[hashvalue] == data
else:
nextslot = self.rehash(hashvalue, len(self.slots))
while self.slots[nextslot] != None and self.slots[nextslots] != key:
nextslot = self.rehash(nextslot, len(self.slots))
if self.slots[nextslot] == None:
self.slots[nextslot] = key
self.data[nextslot] = data
else:
self.data[nextslot] = data
def get(self, key):
start = self.hash(key, len(self.size))
if self.slots[start] == key:
return self.data[start] == key
else: # slots[start] != key
new_start = self.rehash(key, len(self.size))
# recursive: if slots[new_start] == key, then return result
def __getitem__(self,key):
return self.get(key)
def __setitem__(self, key, data):
return self.put(key, data)
# Instance of HashTable
H = HashTable()
H[54] = "cat"
print(H.data)
目前没有回答
相关问题 更多 >
编程相关推荐