LoginSignup
0
2

More than 5 years have passed since last update.

Python:lambdaでfoldl,foldrを作ってみる。あと時間計測とかも

Last updated at Posted at 2015-05-27

Pythonをさわり始めたついでの演習問題。やってみる。

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)) )
    )
)

できた。結構素直にいけて拍子抜け。
いや、すごいH本カンニングしながらでした。自前ではとてもとても...

自前計測ツール

元々あるreduceとかsumとかと比べてみる。
timeitというのが使えるそうだが、IDLE上でどうしていいか分からなかったので、自前で計測ツールを作ってみる。
まあ、何かの練習にはなるでしょう。

import time

measure_t=(lambda f , *arg :
    (lambda m_start = time.time() ,
         m_stop = time.time :
            ( f( *arg),
            m_stop() - m_start ,
            )[-1]
     )()
   )

できた。
関数の実行のタイミングでプチはまる。

  • 計測したい関数fと引数*argを別に渡してここぞ!というときに実行。
  • その前で一回time.time()してm_startに代入しておく。
  • m_stopは定義だけしておいてf()実行後に実行。
  • 最後にかかった時間を返す。

適当に作った割には使いまわせそう。

測ってみた。

>>> 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
  • foldl,foldrは大体同じぐらい。
  • reduceはその三倍ぐらい速い。
  • sumはさらにその十倍速い。(独自調査)

おとなしく極力builtins使うのが吉。ということでしょうか...

以上です。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2