我有一个任务,我要做的是做一个哈希表(哈希值x^2%表大小),当给定一个键值时,我必须将它添加到哈希表中。但是,如果两个键具有相同的hashvalue,我就必须在哈希表的那个槽中创建一个链表。这是我的密码。。。在class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
temp = self.head
self.head = Node(data)
self.head.next = temp
def __str__(self):
str_list = []
current = self.head
while current:
str_list.append(str(current.data))
current = current.next
return "[" + "->".join(str_list) + "]"
# Implement the missing functions in the ChainedHashTable ADT
class ChainedHashTable:
def __init__(self, size):
self.links = [None] * size
self.size = size
def insert(self, key):
#Make 'lst' equal to LL/None at given key in hash table
lst = self.links[self.hash(key)]
#Check to see if spot at hash table is None. If so, make new LL.
if lst == None:
lst = LinkedList()
node = Node(key)
lst.add(node)
self.links[self.hash(key)] = lst
return
#Else append key to already existing linked list.
node = Node(key)
lst.add(node)
return
def hash(self, key):
hash_code = (key*key) % self.size
print(lst)
return hash_code
# Sample testing code
# You should test your ADT with other input as well
cht = ChainedHashTable(11)
cht.insert(1)
cht.insert(36)
cht.insert(3)
cht.insert(44)
cht.insert(91)
cht.insert(54)
cht.insert(18)
print(cht)
当打印(cht)发生时,我得到以下错误。。。在
^{pr2}$
输出应该是。。。在[[44], [54->1], None, None, None, [18], None, None, None, [91->3->36], None]
注意:正在添加。。。在def __repr__(self):
return str(self.links)
给我一个错误:超过了最大递归深度。在
如果你能帮我,万分感谢。在def __repr__(self):
final_list = []
for i in range(len(self.links)):
if self.links[i] == None:
final_list.append('None')
else:
link_list = self.links[i]
string = link_list.__str__()
final_list.append(string)
return ', '.join(final_list)
有了这个密码,我得到了以下信息。。
[<;main.Node object at 0x0000000002E5C518>;][<;main节点对象位于0x0000000002E5C5F8>;->;main。节点对象位于0x0000000002E5C558>;]noneNone[<;main。节点对象位于0x0000000002E5C6A0>;]noneNone[<;main.Node对象位于0x0000000002E5C588>;->;main。节点对象位于0x0000000002E5C470>;->;main。节点对象位于0x0000000002E5C400>;]无
为什么它不把链表的内容转换成一个字符串(使用给定的函数),然后将该字符串赋回自我链接[i] 是吗?我看不出问题出在哪了。。在
已解决
当我将节点添加到链接列表时,我添加的是节点对象而不是节点数据。谢谢你们的反馈!在