Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to compare sequences

Tags:

python

Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:

def comp1(a, b):
    if len(a) != len(b):
        return False
    for i, v in enumerate(a):
        if v != b[i]:
            return False
    return True

The following is a bit shorter, but also less efficient since a third sequence is created:

def comp2(a, b):
    for l, r in map(None, a, b):
        if l != r:
            return False
    return True

Shoehorning one of those examples into a list comprehension isn't really what I'm looking for either.

Edit: Ideally I am looking for a solution that doesn't create another sequence during the comparison.

like image 863
schickb Avatar asked May 22 '09 23:05

schickb


1 Answers

Apart from the extra memory used by creating temporary lists/tuples, those answers will lose out to short circuiting generator solutions for large sequences when the inequality occurs early in the sequences

from itertools import starmap, izip
from operator import eq
all(starmap(eq, izip(x, y)))

or more concisely

from itertools import imap
from operator import eq
all(imap(eq, x, y))

some benchmarks from ipython

x=range(1000)
y=range(1000); y[10]=0

timeit tuple(x) == tuple(y)
100000 loops, best of 3: 16.9 us per loop

timeit all(imap(eq, x, y))
100000 loops, best of 3: 2.86 us per loop
like image 163
John La Rooy Avatar answered Sep 20 '22 14:09

John La Rooy