[Tutor] lazily decorated sort

eryksun eryksun at gmail.com
Fri Sep 28 16:38:02 CEST 2012


On Fri, Sep 28, 2012 at 8:17 AM, Peter Otten <__peter__ at web.de> wrote:
>
> def make_key(keys):
>     @total_ordering
>     class Key(object):
>         def __init__(self, value):
>             self._keys = keys(value)
>             self._cached = []


Using a generator/iterator to pump the key values into a cache is a
great idea. But I think it would generally be nicer to let "keys" be a
sequence of functions. Then define the generator in make_key() before
you define the class:


    def make_key(keys):

        def _keys(value):
            for key in keys:
                yield key(value)

        @total_ordering
        class Key(object):

            def __init__(self, value):
                self._keys = _keys(value)
                self._cached = []


Also, as far as I can see in the code, implementing "total_ordering"
is unnecessary for sorting. One only needs to implement __lt__. It's
used by binarysort() to test the pivot via the IFLT/ISLT macros:

http://hg.python.org/cpython/file/70274d53c1dd/Objects/listobject.c#l1023


>         def __lt__(self, other):
>             for a, b in izip(self.keys(), other.keys()):
>                  if a == b:
>                      pass
>                  else:
>                      return a < b
>             return False


Or test for "!=":

        def __lt__(self, other):
            for a, b in izip(self.keys(), other.keys()):
                 if a != b:
                     return a < b
            return False


More information about the Tutor mailing list