我正在尝试使用以下代码创建一个哈希表,但是当我创建它的一个实例时,我得到一个:
TypeError:并非在字符串格式化期间转换所有参数
我不太确定我哪里出错了;我使用函数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)