Lisp mentality vs. Python mentality

namekuseijin namekuseijin.nospam at gmail.com
Sun Apr 26 08:26:40 CEST 2009


Ciprian Dorin, Craciun wrote:
> On Sun, Apr 26, 2009 at 7:54 AM, Steven D'Aprano
> <steve at 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



More information about the Python-list mailing list