python 3.x - Python3, map-function -


i'm trying optimize piece of code speed (and correctness, of course) in python3:

from math import log timeit import timer  def groffle_slow(mass, density):     total = 0.0     in range(10000):         masslog = log(mass * density)         total += masslog/(i+1)     return total 

i've been amazed @ how map speeds things up, so...

def groffle_faster(mass, density):     total = 0.0     masslog = log(mass * density)     return map(sum, (masslog/(i+1) in range(10000))) 

looking @ difference in time of execution, there's no comparison. groffle_faster() waaay faster, it's returning map object. map object should contain sum float.

anyway can float out of map object?

thanks!

it's waaay faster because it's not doing anything; , if were, wouldn't work.

>>> mass = 1.2 >>> density = 2.3 >>> masslog = math.log(mass * density) >>> map(sum, (masslog/(i+1) in range(10000))) <map object @ 0x7feccaf1fc18> 

this map object lazy object yield results of function sum applied each element of iterable, in case generator expression (masslog/(i+1) in range(10000)). no calculations have been done.

but doesn't make sense here anyway, because you're trying apply sum function each element individually, , so:

>>> list(map(sum, (masslog/(i+1) in range(10000)))) traceback (most recent call last):   file "<ipython-input-13-c0f9c805843a>", line 1, in <module>     list(map(sum, (masslog/(i+1) in range(10000)))) typeerror: 'float' object not iterable 

what want simply

>>> sum(masslog/(i+1) in range(10000)) 9.936677928893602 

which give

>>> %timeit groffle_slow(1.5, 2.5) 100 loops, best of 3: 5.08 ms per loop >>> %timeit groffle_fast(1.5, 2.5) 100 loops, best of 3: 3.02 ms per loop 

but since sum(1/(i+1) in range(10000)) fixed number, i'm not sure why don't use like

>>> def groffle_o1(mass, density): ...     msum = 9.787606036044345 ...     return log(mass*density) * msum ...  >>> %timeit groffle_o1(1.5, 2.5) 1000000 loops, best of 3: 424 ns per loop 

but haven't specified constraints you're operating under, it's hard know real problem is.


Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -