[Tutor] remove function
Kent Johnson
kent37 at tds.net
Thu Jul 27 13:08:12 CEST 2006
Christopher Spears wrote:
> My apologies to everyone. Here is the complete code:
>
>
> class PriorityQueue:
> def __init__(self):
> self.items = []
>
> def isEmpty(self):
> return self.items == []
>
> def insert(self, item):
> self.items.append(item)
>
> def remove(self):
> maxi = 0
> for i in range(1, len(self.items)):
> if self.items[i] > self.items[maxi]:
> maxi = i
> item = self.items[maxi]
> self.items[maxi:maxi+1] = []
> return item
>
Slice indexing in Python is up-to-but-not-including. So
self.items[maxi:maxi+1] = []
means, replace the slice of self.items, that starts at maxi and goes up
to but not including maxi+1, with the empty list. So it is effectively
deleting self.items[maxi], which could also be written as
del self.items[maxi]
or combine it with the line above as
item = self.items.pop(maxi)
By the way if this class is for production use, rather than learning,
you should look into the heapq module, it implements a much more
efficient algorithm than the one above. heapq implements a min heap, not
a max heap, so you need some kind of wrapper for your items to get them
in the order you want.
Kent
More information about the Tutor
mailing list