You can use the generator:
import itertools def apply_apply(f, x_0): x = x_0 while True: yield x x = f(x) .... y = list(itertools.islice(apply_apply(f, x), N))
Another way is to switch to a fully functional route:
from functools import reduce y = list(reduce(lambda x, f: x + [f(x[-1])], [[x_0]] + [f] * (N - 1)))
As a side note, both solutions work better on my machine than the decision made, for 2 ms for the generator, 2 ms for the functional and 4 ms for the Raymond code with f = lambda x: x * x , x_0 = 2 and N = 20 .
For lambda x: 2 * x Raymond version is slightly faster than the generator approach, and much faster than the functional version. It seems to depend on the complexity of f , although I don't know how ...
source share