Python implements heap (simple version)

principle

I always use heaps in algorithm questions, but I always use the small root heap that comes with python. I don’t know much about the principle of heaps, so I have a good foundation and write codes by myself so that I can have a deeper understanding.

In terms of principle, I mainly refer to the following blogs:
Data structure - heap (heap) and Python implementation of heap
Python implements heap insertion, deletion, and creation

In addition, since you refer to other people's open source ideas for things like technology, you must respect the originality. Everyone learns from a rookie step by step. It is not a shame to refer to the content of the predecessors
.

Also, I don't understand why someone has to set their blog to be visible only to fans. Is it so important to have more fans? If the article is well written, people will naturally be willing to follow you; the overall level is like that, even if you have to follow because of a certain blog, it will be canceled later. It is recommended not to engage in these boring things

the code

There are still many functions in the code that have not been added, and some logic is not elegant enough. It is the most basic version. Because of the small number of functions, it is also helpful to understand the principle of the heap

class minheap:
    
    def __init__(self):
        self.q = []
    
    def heapinsert(self, val):
        self.q.append(val)
        self.totop()
    
    def totop(self):
        i = len(self.q)-1
        while i > 0:
            father = (i-1) // 2
            if self.q[i] < self.q[father]:
                self.q[i], self.q[father] = self.q[father], self.q[i]
                i = father
            else:
                break
    
    def heappop(self):
        if not self.q:
            raise Exception('The heap is empty!')
        last = len(self.q)-1
        self.q[0], self.q[last] = self.q[last], self.q[0]
        res = self.q.pop()
        self.todown()
        return res
    
    def todown(self):
        i = 0
        while 2*i+2 < len(self.q):
            left = 2*i+1
            right = 2*i+2
            # 分情况讨论,判断i去往左孩子还是右孩子
            if self.q[left] < self.q[i] and self.q[left] <= self.q[right]:
                self.q[i], self.q[left] = self.q[left], self.q[i]
                i = left
            elif self.q[right] < self.q[i] and self.q[right] <= self.q[left]:
                self.q[i], self.q[right] = self.q[right], self.q[i]
                i = right
            else:
                break
        # 如果还有左孩子
        left = 2*i+1
        if left < len(self.q) and self.q[left] < self.q[i]:
            self.q[i], self.q[left] = self.q[left], self.q[i]



if __name__ == '__main__':
    import random
    
    # 测试10000次
    for _ in range(10000):
    
        # 生成随机长度随机数组
        arr = []
        for _ in range(random.randint(1,100)):
            arr.append(random.randint(1,100))
        # print(arr)
        
        n = len(arr)
        q = minheap()
        
        for i in arr:
            q.heapinsert(i)
        # print(q.q)
        
        res = []
        for _ in range(n):
            res.append(q.heappop())
        # print(res)
        
        if sorted(arr) != res:
            print('something wrong!')
    
    print('success!')

Guess you like

Origin blog.csdn.net/qq_45510888/article/details/124460201