Ciprian Dorin, Craciun wrote:
On Sun, Apr 26, 2009 at 7:54 AM, Steven D'Aprano
<st...@remove-this-cybersource.com.au> wrote:
    I liked very much your implementation for the compare function, it
is very short and at the same time readable:

def compare(a, b, comp=operator.eq):
    return (len(a) == len(b)) and all(comp(*t) for t in zip(a, b))

    But I have only one problem, it is suboptimal, in the sense that:
    * it constructs two intermediary lists (the list comprehension and
the zip call);

    * it evaluates all the elements, even if one is false at the beginning;

This evaluates just until finding one that is false:

return (len(a) == len(b)) and not any(not comp(*t) for t in (zip(a, b)))

plus the zip call enclosed in parentheses got turned into an iterator.

>>> def compare(a, b, comp=operator.eq):
... return (len(a) == len(b)) and not any(not comp(a,b) for (a,b) in (zip(a, b)))
...
>>> compare( [1,2,3], [1,3,3] )
False
>>> compare( [1,2,3], [1,2,3] )
True
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to