Exercises while starting to touch Python. Try. foldl,foldr
box=lambda *x:x
unbox=lambda x:x[-1]
do=box
switch=unbox
foldl=(lambda f,acc,xs:
switch(
xs == [] and do( acc )
or do( foldl(f, f(acc, xs[0]), xs[1:]) )
)
)
foldr=(lambda f,xs,acc:
switch(
xs == [] and do( acc )
or do( foldr(f, xs[:-1], f(xs[-1], acc)) )
)
)
did it. I can go straight and miss the beat. No, it was amazing H book cheating. Very very on my own ...
Compare it with the original reduce or sum. It seems that timeit can be used, but I didn't know what to do on IDLE, so I'll try to make my own measurement tool. Well, it will be some practice.
import time
measure_t=(lambda f , *arg :
(lambda m_start = time.time() ,
m_stop = time.time :
( f( *arg),
m_stop() - m_start ,
)[-1]
)()
)
did it. Petit fits at the timing of function execution.
It seems that it will be used even though it is made properly.
>>> measure_t(foldl,lambda x,y:x+y,0,range(1,100))
0.00026679039001464844
>>> measure_t(foldr,lambda x,y:x+y,range(1,100),0)
0.000247955322265625
>>> measure_t(reduce,lambda x,y:x+y,range(100))
7.605552673339844e-05
>>> measure_t(sum,range(100))
6.198883056640625e-06
It is good to use builtins as quietly as possible. Does that mean ...
that's all.
Recommended Posts