【问题标题】:my custom heapify method not working properly in python我的自定义 heapify 方法在 python 中无法正常工作
【发布时间】:2022-01-22 04:28:57
【问题描述】:

我正在学习数据结构,但我的代码无法正常工作..我尝试调试但找不到任何东西(似乎 heapifyinsert() 没有做任何事情)

这是我的代码:

class Heap:
    def __init__(self,size):
        self.heap=[None]*(size+1)
        self.heapsize=0
        self.maxheapsize=size+1


    def levelordertransversal(self):
        if not self.heap:
            raise Exception('Heap doesn\'t exists')
        for x in range(1,self.heapsize+1):
            print(self.heap[x])

    def heapifyinsert(self,index,heaptype):
        heaptype=heaptype.title()
        parentindex=int(index/2)
        if parentindex<=1:
            return
        if heaptype=='Min':
            if self.heap[index]<self.heap[parentindex]:
                temp=self.heap[index]
                self.heap[index]=self.heap[parentindex]
                self.heap[parentindex]=temp
            self.heapifyinsert(parentindex,heaptype)
        elif heaptype=='Max':
            if self.heap[index]>self.heap[parentindex]:
                temp=self.heap[index]
                self.heap[index]=self.heap[parentindex]
                self.heap[parentindex]=temp
            self.heapifyinsert(parentindex,heaptype)

    def insertnode(self,nodevalue,heaptype):
        if self.heapsize+1==self.maxheapsize:
            raise Exception('Heap is full!!')
        self.heap[self.heapsize+1]=nodevalue
        self.heapsize+=1
        self.heapifyinsert(self.heapsize,heaptype)

h=Heap(5)
h.insertnode(4,'Max')
h.insertnode(5,'Max')
h.insertnode(2,'Max')
h.insertnode(1,'Max')
h.levelordertransversal()

当前输出:

4
5
2
1

预期输出:

5
4
2
1

因此,在上面的代码中,我尝试从索引位置 1 开始实现堆(为简单起见),在 heapifyinsert() 方法中,我们采用 parentindex 并检查父索引处的值是否更大或更小堆类型和交换值

任何帮助或线索将不胜感激..谢谢!

【问题讨论】:

  • 您希望heaptype=heaptype.title() 的结果是什么?此指令更改作为变量提供给函数的 heaptype 的值。
  • @itprorh66 先生,这个想法是用户可以输入堆类型而不管它是什么情况(bcz先生,函数内部堆类型的条件写在标题中)
  • 好吧,每天都学点新东西。

标签: python data-structures heap


【解决方案1】:

问题是递归停止得太快了。 1 是堆中的有效索引,而 0 不是,这意味着您需要更改:

if parentindex<=1:

...到:

if parentindex< 1:

这将解决问题。

您的代码中的其他一些 cmets:

  • 当孩子和父母之间的比较正常时,递归可以停止。所以将self.heapifyinsert(parentindex,heaptype) 的调用移到前面的if 块内。

  • 不应为insertnode 定义heaptype 参数,因为显然为insertnode 的下一次调用提供不同的值是没有意义的:它应该始终为“Min”或始终为“最大限度”。所以这应该是构造函数的参数,并存储为堆的属性

  • 在 Python 中,您可以使用元组赋值轻松交换值,而无需 temp 变量

  • int(index/2) 将首先执行浮点除法并将其转换回整数。只使用整数除法更有意义:index // 2

  • if not self.heap: 是不必要的:因为heap 属性是由构造函数初始化的,所以这永远不会发生

  • 避免一些代码重复:交换和递归调用是相同的,独立于堆类型,因此请尝试重新排列您的代码,以便仅将其编码一次。

【讨论】:

  • 非常感谢先生再次帮助我:)
猜你喜欢
  • 2015-01-28
  • 1970-01-01
  • 2016-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多