Python 什么';堆的这种实现有什么问题?
我的插入方法不正确,我不知道为什么。 my min方法错误,且“内置函数或对象不可下标” 我认为我对堆的概念性理解是可以的。但实际上写下来时,它的水力压裂令人沮丧:(Python 什么';堆的这种实现有什么问题?,python,heap,Python,Heap,我的插入方法不正确,我不知道为什么。 my min方法错误,且“内置函数或对象不可下标” 我认为我对堆的概念性理解是可以的。但实际上写下来时,它的水力压裂令人沮丧:( 类堆: 定义初始化(自): self.array=[] def find_子项(自我,索引): “”“返回左右两个子项”“” 返回索引*2+1,索引*2+2 def插入(自身,值): “”“将节点值附加到数组中,然后弹出气泡。” 回到它应有的位置 """ self.array.append(值) index=self.array.
类堆:
定义初始化(自):
self.array=[]
def find_子项(自我,索引):
“”“返回左右两个子项”“”
返回索引*2+1,索引*2+2
def插入(自身,值):
“”“将节点值附加到数组中,然后弹出气泡。”
回到它应有的位置
"""
self.array.append(值)
index=self.array.index(值)
当索引>0或self.array[index]
插入中的self.array.index(value)
行是危险的。如果插入堆中已经存在的值,会发生什么情况?应该改用len(self.array)
(您将附加到数组中,因此它将是最后一个元素)
类似地,在min
中,您也可以有效地执行相同的操作。您不需要搜索该索引,您已经知道了
实际上,您可能希望维护自己的“长度”和“容量”属性,因为增大和缩小备份数组会在预期的日志(n)上跺脚。您在self.array.index[最小值]上使用了错误的括号只是为了澄清下一个投票:错误应该精确地说明了问题所在。省略这些信息,而只是把代码倾倒给别人去做是不礼貌的。经销商的选择是:不是A,没有适当的回溯,琐碎的排字者认为自己投了一个太大的问题而被问到一个太大的问题。de也是。当你不屑于问一个明确的问题时,仅仅是丢弃坏代码,期望其他人修复它,理解你做了什么,理解你一直在尝试做什么,并解释所有这三件事……不完全是礼貌的,或者至少是礼貌的,或者是离开。“算法正确吗?”-您不可能在代码无法正常工作的情况下自行确定。您考虑过测试它吗?
class Heap:
def __init__(self):
self.array = []
def find_children(self, index):
""" return both the left and right children """
return index * 2 + 1, index * 2 + 2
def insert(self, value):
""" append node value to the array, then bubble up
to its rightful place
"""
self.array.append(value)
index = self.array.index(value)
while index > 0 or self.array[index] < self.array[index // 2 - 1]:
if self.array[index] < self.array[index // 2 - 1]:
temp = self.array[index]
self.array[index] = self.array[index // 2 - 1]
self.array[index // 2 - 1] = temp
index = index // 2 - 1
def min(self):
""" remove the min at the root, then bubble down to
maintain heap property
"""
minimum = self.array[0]
self.array[0] = self.array[-1]
self.array.pop()
index = self.array.index[minimum]
while index <= len(self.array):
leftChildIndex, rightChildIndex = self.find_children(index)
minChild = min( self.array[leftChildIndex], self.array[rightChildIndex] )
if self.array[index] > minChild:
temp = self.array[index]
self.array[index] = minChild
minChild = temp
index = minChild
return minimum
def p(self):
return self.array