python基础学习---实现优先队列

使用堆实现优先队列:

# coding: utf-8

import heapq

class PriorityQueue(object):

    def __init__(self):
        self.queue = []
        self._index = 0

    def push(self, item, pri):
        heapq.heappush(self.queue, (-pri, self._index, item))
        self._index += 1

    def pop(self):
        return heapq.heappop(self.queue)[-1]


if __name__ == '__main__':
    pri = PriorityQueue()
    pri.push("2222", 2)
    pri.push("1111", 1)
    print(pri.pop())
    print(pri.pop())
 # 2222
 # 1111

你可能感兴趣的:(python)