MacPython Logo from __future__ import *

buy music albums Silver Apples buy mp3 albums Tarrus Riley buy tracks mp3 Kravits buy Reaper albums mp3 buy Kravits albums music buy music Evita CD online albums mp3 Silver Apples download Madonna CD music buy tracks music Kravits download music albums Silver Apples

2003-11-19

Comparing iterables

Filed under: python — bob @ 2:10 pm

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

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Protected by WP-Hashcash.

Powered by WordPress