A note on heapq module

Antoon Pardon apardon at forel.vub.ac.be
Wed Jan 17 07:18:01 EST 2007


On 2007-01-16, bearophileHUGS at lycos.com <bearophileHUGS at lycos.com> wrote:
> In few minutes I have just written this quite raw class, it lacks
> doctring (the same of the functions of the heapq module), it may
> contain bugs still, I haven't tested it much. It's just a simple
> wrapper around some of the functions of the heapq module (nsmallest and
> nlargest are missing). Usually I use classes only when I need then, I
> like functional programming enough, and this class seems to just slow
> down the functions of the heapq module. But I think an improved class
> similar to this one may be useful (added, replacing isn't necessary)
> into the heapq module, because it can avoid cetain errors: I know what
> Heaps are and how they work, but some time ago I have written a bug
> into small program that uses the functions of the heapq module, because
> I have added an item to the head of the heap using a normal list
> method, breaking the heap invariant. With a simple class like this one
> all the methods of your object keep the heap invariant, avoiding that
> kind of bugs. (If you are interested I can improve this class some,
> it't not difficult.)
>
> [ Heap class based on heapq ]

For me, your class has the same drawback as the heappush, heappop
procedurers: no way to specify a comparision function. Somewhere
in my experimental code I work with line segments in two dimensions.
Now in one place I want from the available segments the one in which the
first point is farthest to the left. In a second place I want from the
available segments the one in which the second point is farthest to the
left. Both can be done with a heap, but currently I can't get both
behaviours while using the same class and using the heapq module or
your Heap class.

-- 
Antoon Pardon



More information about the Python-list mailing list