Priority Queue and Heap in Python

  1. Two kinds of priority queue implementation:
from queue import PriorityQueue
import heapq
  1. Heapq
    Visit for details: https://docs.python.org/3/library/heapq.html
    Heapq functions are directly applied to list. You can create a normal list, can convey it into functions in heapq package.

    You can get the top element simply by heap[0].
    Heapq uses min for top. You can negate them to maintain max for top.
    heappush: O(log(n))
    heappop: O(log(n)). Actually it first pop the last one of the list and then replace the top element with it and then siftup and siftdown.
    heappushpop(heap, item): push then pop. Length does not change. O(log(n))
    heapreplace(heap, item): pop then push. Length does not chagne. O(log(n))
    heapify(list): transform a list to heap inplace. O(n) time complexity. (heap sort is O(nlog(n)) because you need to delete the top element one by one after building the heap). For a already arranged heap, if you heapify it, you will still sift up and sift down all the elements.
    heapq.nlargest(n, iterable, key=None): find the n largest ones in a list.
    heapq.nsmallest(n, iterable, key=None): find the n smallest ones in a list.

Deletion: if you want to delete a special position in the heap, you need to copy the siftup and siftdown function in the source code of heapq, and then use the last element to replace the special element, and then sift up and sift down it. But when u sift down it, you need to set the start position to be the root position because the last element may be smaller than the parent of the node you replace.

In heappop, siftup till the leaf first and then siftdown is better than classical heap sift because you only conduct one comparison in each sift (only compare two childs in siftup and only compare one child and parent in siftdown).

If you want to maintain a fixed length priority queue, you need to write codes to check whether the maximal length is reached. When it is reached, you can use heapq.pushpop() to add the new element.

  1. PriorityQueue
    See for details: https://docs.python.org/3/library/queue.html
    If you put item in a full PQ, or get item from a empty PQ, there will be block.
    You cannot get the top element without pop.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值