Python利用heapq实现一个优先级队列的方法

yipeiwu_com5年前Python基础

实现一个优先级队列,每次pop的元素要是优先级高的元素,由于heapq.heapify(list)默认构建一个小顶堆,因此要将priority变为相反数再push,代码如下:

import heapq
class PriorityQueue(object):
  """实现一个优先级队列,每次pop优先级最高的元素"""
  def __init__(self):
    self._queue = []
    self._index = 0
  def push(self,item,priority):
    heapq.heappush(self._queue,(-priority,self._index,item))#将priority和index结合使用,在priority相同的时候比较index,pop先进入队列的元素
    self._index += 1
  def pop(self):
    return heapq.heappop(self._queue)[-1]
if __name__ == '__main__':
  pqueue = PriorityQueue()
  pqueue.push('d',4)
  pqueue.push('f',3)
  pqueue.push('a',6)
  pqueue.push('s',2)
  print(pqueue.pop())
  print(pqueue.pop())
  print(pqueue.pop())

Python利用heapq实现一个优先级队列

以上这篇Python利用heapq实现一个优先级队列的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python和JavaScript间代码转换的4个工具

Python和JavaScript间代码转换的4个工具

选 Python 还是 JavaScript?虽然不少朋友还在争论二者目前谁更强势、谁又拥有着更为光明的发展前景,但毫无疑问,二者的竞争在 Web 前端领域已经拥有明确的答案。立足于浏览...

Django 源码WSGI剖析过程详解

Django 源码WSGI剖析过程详解

前言 python 作为一种脚本语言, 已经逐渐大量用于 web 后台开发中, 而基于 python 的 web 应用程序框架也越来越多, Bottle, Django, Flask 等...

基于Python 装饰器装饰类中的方法实例

基于Python 装饰器装饰类中的方法实例

title: Python 装饰器装饰类中的方法 comments: true date: 2017-04-17 20:44:31 tags: ['Python', 'Decorate'...

python使用post提交数据到远程url的方法

本文实例讲述了python使用post提交数据到远程url的方法。分享给大家供大家参考。具体如下: import sys, urllib2, urllib zipcode = "S2...

解决torch.autograd.backward中的参数问题

解决torch.autograd.backward中的参数问题

torch.autograd.backward(variables, grad_variables=None, retain_graph=None, create_graph=False...