[Tutor] Re: Case study: writing an Python extension type in C [C extensions / priority queues / PyHeap]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 20 Apr 2002 23:53:16 -0700 (PDT)


> ###
> class PriorityQueue:
>     """This is a simple implementation of a priority queue."""
>
>     def __init__(self, cmp=cmp):
>         self.cmp = cmp
>         self.items = []
>
>     def push(self, obj):
>         self.items.append(obj)
>         self.items.sort(cmp)
>
>     def pop(self):
>         return self.items.pop()
> ###
>
>
> No sweat.  *grin* And this works well enough:


Doh.  I hate hubris; I spoke too soon again.  There's a bug in push():

>     def push(self, obj):
>         self.items.append(obj)
>         self.items.sort(cmp)
                          ^^^

I meant to write:

     def push(self, obj):
         self.items.append(obj)
         self.items.sort(self.cmp)



Sorry about that.  Here's the correction version of a sort-based
PriorityQueue class:

###
class PriorityQueue:
    """This is a simple implementation of a priority queue."""

    def __init__(self, cmp=cmp):
        self.cmp = cmp
        self.items = []

    def push(self, obj):
        self.items.append(obj)
        self.items.sort(self.cmp)

    def pop(self):
        return self.items.pop()
###