[BangPypers] if not with comparision statement in python

Noufal Ibrahim noufal at gmail.com
Tue Aug 2 08:24:45 CEST 2011


Anand Balachandran Pillai <abpillai at gmail.com> writes:

[...]

>  1. List comp
>
>  >>> sum([x*x for x in range(10)])
>  285
>
>  2. Map
>
>  >>> sum(map(lambda x: x*x, range(10)))
>  285
>
>  3. Reduce
>
>  >>> reduce(lambda x,y: x + y*y, range(10))
>  285

A quote from Guido

"filter(P, S) is almost always written clearer as [x for x in S if P(x)]"

I'm not sure about that but what the heck.

Also, 

The first one should be

   sum(x*x for x in xrange(10))


>>> def f1(): return sum([x*x for x in range(1,10)])
...
>>> def f2(): return sum([x*x for x in xrange(1,10)])
...
>>> def f3(): return sum(x*x for x in xrange(1,10))
...

>>> import timeit
>>> timeit.timeit(f1, number = 100000)
0.20368003845214844
>>> timeit.timeit(f2, number = 100000)
0.17799496650695801
>>> timeit.timeit(f3, number = 100000)
0.17561507225036621




[...]


-- 
~noufal
http://nibrahim.net.in

I must follow the people. Am I not their leader? -Benjamin Disraeli


More information about the BangPypers mailing list