【发布时间】:2014-04-20 10:20:00
【问题描述】:
我有一个任务,我要做的是制作一个哈希表(哈希值 x^2 % tablesize),当给定一个键值时,我必须将它添加到哈希表中。但是,如果两个键具有相同的哈希值,我必须在哈希表中的那个槽处创建一个链表。这是我的代码...
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)
发生 print(cht) 时出现以下错误...
<__main__.ChainedHashTable object at 0x0000000002D9E2B0>
输出应该是……
[[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 对象位于 0x0000000002E5C518>][main.Node 对象位于 0x0000000002E5C5F8>->main.Node 对象位于 0x0000000002E5C358> ]NoneNoneNone[main.Node 对象位于 0x0000000002E5C6A0>]NoneNoneNone[main.Node 对象位于 0x0000000002E5C588>->main.Node 对象在 0x0000000002E5C470>->main.Node 对象在 0x0000000002E5C400>]None
为什么不将链表的内容转换为字符串(具有给定函数),然后将该字符串分配回 self.links[i]?我看不出代码中的问题出在哪里..
已解决 当我将节点添加到我的链表时,我添加的是节点对象而不是节点数据。感谢您的反馈!
【问题讨论】:
-
不要通过
links并用字符串替换条目。如果您这样做,您的所有数据都会丢失。你只剩下字符串了。 -
那你有什么建议?
-
创建一个新列表以供展示!
-
嘿,我修改了那里的代码。我不会以任何方式修改 self.links - 我只是从中提取值。现在,我不知道为什么它不起作用......我什至尝试将 __str__() 代码直接放入 repr 函数中,但结果是一样的。好消息是,我的所有节点都在正确的位置,所以,我的输出是正确的,我只需要正确打印它。
标签: python hashtable singly-linked-list