from __future__ import * 19.11.2003

2003-11-19

Comparing iterables

Python doesn't have a way to compare arbitrary iterables (without converting them to a tuple or list). It's also easy to get it wrong if you try and do it with itertools (since imap and izip will consume an extra element from the first sequence if it's longer). Here's how to do it right:

from itertools import ifilter, imap, chain

class StopToken:
    def __cmp__(self, other):
        if self is other:
            return 0
        return -1
StopToken = StopToken()

def cmpseq(a, b, StopToken=StopToken):
    a, b = chain(a, (StopToken,)), chain(b, (StopToken,))
    for rval in ifilter(None, imap(cmp, a, b)):
        return rval
    try:
        a.next()
        return 1
    except StopIteration:
        try:
            b.next()
            return -1
        except StopIteration:
            return 0
posted at 11:10:40    #    comment []    trackback []
November
MoTuWeThFrSaSu
      1 2
3 4 5 6 7 8 9
10111213141516
17181920212223
24252627282930
Oct Dec

Bob's Rants

XML-Image Letterimage

© 2003-2004, Bob Ippolito