Welcome, guest | Sign In | My Account | Store | Cart

heapq is a nice python module, but the interface is not so clean. I found a one-liner on this blog, it's as short as possible, but not really pythonic either :) Here is my contribution to a most readable heap class.

Python, 17 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import heapq

class Heap(list) :
	def __init__(self, * pos_arg, ** nam_arg) :
		list.__init__(self, * pos_arg, ** nam_arg)
		
	def pop(self) :
		return heapq.heappop(self)
		
	def push(self, item) :
		heapq.heappush(self, item)
		
	def pushpop(self, item) :
		return heapq.heappushpop(self, item)
		
	def poppush(self, itemp) :
		return heapq.replace(self, item)
	

3 comments

James Mills 10 years, 5 months ago  # | flag

I wonder if this also supports priorities. I'd also like to see a heapq implemtantion in Python with a more intuative priority ordering.

pavel 10 years, 4 months ago  # | flag

Sorry, 8-chars indentation looks ugly.

yota (author) 10 years, 4 months ago  # | flag

It's not 8 space indented, but one tab :)

As such, you can set your editor to whatever-you-want-and-I-don't-need-to-care tab size. Space indentation kills kittenz :D

Created by yota on Wed, 23 Oct 2013 (GPL3)
Python recipes (4591)
yota's recipes (13)

Required Modules

Other Information and Tasks

  • Licensed under the GPL 3
  • Viewed 8881 times
  • Revision 2 (updated 8 years ago)