编程语言
首页 > 编程语言> > python heapq 有序队列

python heapq 有序队列

作者:互联网

python库 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__的符号顺序

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)

标签:__,heapq,python,self,队列,heappush,MyObj,cmp
来源: https://blog.csdn.net/duoyasong5907/article/details/113451853