A note on heapq module

Scott David Daniels scott.daniels at acm.org
Tue Jan 16 13:32:41 EST 2007


bearophileHUGS at lycos.com wrote:
> In few minutes I have just written this quite raw class, ....
I'd suggest some changes.  It is nice to have Heaps with equal
contents equal no matter what order the inserts have been done.
Consider how you want Heap([1, 2, 3]) and Heap([3, 1, 2]) to behave.
Similarly, it is nice to have str and repr produce canonical
representations (I would skip the __str__ code, myself, though).
Also, subclasses should get their identities tweaked as so:

> class Heap(object):
>     ...
>     def sort(self, cmp=None, key=None):
>         self.h.sort(cmp=cmp, key=key)
I'd remove this method.
>     ...
>     def __eq__(self, other):
>         return isinstance(other, Heap) and self.h == other.h
           return isinstance(other, self.__class__) and sorted(
                                      self.h) == sorted(other.h)
>     def __ne__(self, other):
>         return not isinstance(other, Heap) or self.h != other.h
           return not isinstance(other, self.__class__) and sorted(
                                      self.h) != sorted(other.h)
>     ...
>     def __str__(self):
>         return str(self.h)
           return str(sorted(self.h))
>     def __repr__(self):
>         return "Heap(%s)" % self.h if self.h else "Heap()"
           return "%s(%s)" % (self.__class__.__name__, sorted(self.h))
And I'd add:
       def __lt__(self, other):
           raise TypeError('no ordering relation is defined for %s'
                           % self.__class__.__name__)
       __gt__ = __le__ = __ge__ = __lt__

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list