On Mon, Mar 14, 2011 at 1:39 PM, Paul Rubin <no.email@nospam.invalid> wrote:
> Finally I concocted an "infinite" example which we agreed is artificial:
> you are given a list of generators denoting real numbers, for example
> pi generates the infinite sequence 3,1,4,1,5,9... while e generates
> 2,7,1,8,...  You can sort these with cmp but not with key.

I would think that you can sort them with key as long as none of the
sequences are equal (which would result in an infinite loop using
either method).  Why not this?

_MISSING = object()

@functools.total_ordering
class IteratorKey(object):

    def __init__(self, iterable):
        self._iterator = iter(iterable)
        self._cache = []

    def __iter__(self):
        # This is not reentrant, but it's
        # good enough for this purpose.
        for x in self._cache:
            yield x
        for x in self._iterator:
            self._cache.append(x)
            yield x

    def __lt__(self, other):
        for x, y in itertools.izip_longest(self, other, fillvalue=_MISSING):
            if x is _MISSING or y is _MISSING:
                return x is _MISSING
            elif x < y or y < x:
                return x < y
        return False

    def __eq__(self, other):
        for x, y in itertools.izip_longest(self, other, fillvalue=_MISSING):
            if x is _MISSING or y is _MISSING or x != y:
               return False
        return True
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to