utorok 28. septembra 2010

Why using itertools to repeat function call?

import time
import itertools

def fnc(i): time.sleep(1); return i

all([fnc(i) for i in range(10)]) # 10 second although first element is zero

all(map(fnc,range(10))) # also 10 second

# idea is using generator to not create all values in list

all(itertools.imap(fnc,range(10))) # 1 second ! :)

# but from python 2.4 we could change square brackets to parenthesis and get generator!

all
((fnc(i) for i in range(10))) # also 1 second ! :)


Žiadne komentáre:

Zverejnenie komentára