python hash table_Python哈希表和链表。如何从HashTable类打印列表

这篇博客讨论了一个哈希表的实现,其中使用平方取模作为哈希函数。当哈希冲突发生时,通过链表来解决。博客提到了在插入元素时遇到的问题,即在将节点添加到链表时,应该添加节点数据而不是节点对象。经过修正,程序现在能够正确地将链表内容转换为字符串并存储。
摘要由CSDN通过智能技术生成

我有一个任务,我要做的是做一个哈希表(哈希值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] 是吗?我看不出问题出在哪了。。在

已解决

当我将节点添加到链接列表时,我添加的是节点对象而不是节点数据。谢谢你们的反馈!在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值