python heapq 有序队列

python库 heapq算法

还是用queue.PriorityQueue吧, leetcode python3不包含heapq库

本例是heapq的简易用法, heapq默认建立了小根堆

>>> h = []
>>> heappush(h, (5, 'write code'))
>>> heappush(h, (7, 'release product'))
>>> heappush(h, (1, 'write spec'))
>>> heappush(h, (3, 'create tests'))
>>> heappop(h)
(1, 'write spec')

本例中展示了heapq有序队列使用自定义类对象时的操作. 注意自定义类实现__cmp__即可. 注意__cmp__的符号顺序

  • __cmp__比较为小于号时, 建立大根堆
  • __cmp__比较为大于号时, 建立小根堆
import heapq
class MyObj:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __cmp__(self, other):
        return (self.x*10+self.y) > (other.x*10+other.y)

class Solution(object):
    def findLadders(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: List[List[str]]
        """
        q = []
        heapq.heapify(q)  # 列表为空时不用这么做
		
		# push操作
        heapq.heappush(q, MyObj(4, 3))
        heapq.heappush(q, MyObj(1, 2))
        heapq.heappush(q, MyObj(2, 1))

        while q:
            # peek操作, 列表头就是堆顶
            print(q[0].x, q[0].y)

            # pop操作
            next_item = heapq.heappop(q)
            print(next_item.x, next_item.y)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值