Hristo Mohamed
Hristo Mohamed

Reputation: 13

Python iterator that iterates a function

So I must make the following function -> iterate. On first call it should return identity, on second func, on third func.func. Any idea how to do it? I tried looking at the iter and next method buf failed: (

>>> def double(x):
        return 2 * x

>>> i = iterate(double)
>>> f = next(i)
>>> f(3)
3
>>> f = next(i)
>>> f(3)
6
>>> f = next(i)
>>> f(3)
12
>>> f = next(i)
>>> f(3)
24

Upvotes: 1

Views: 150

Answers (1)

Duncan
Duncan

Reputation: 95652

Something like this perhaps:

>>> import functools
>>> def iterate(fn):
    def repeater(arg, _count=1):
        for i in range(_count):
            arg = fn(arg)
        return arg
    count = 0
    while True:
        yield functools.partial(repeater, _count=count)
        count += 1


>>> i = iterate(double)
>>> f, f2, f3, f4 = next(i), next(i), next(i), next(i)
>>> f(3), f2(3), f3(3), f4(3)
(3, 6, 12, 24)
>>> f(3), f2(3), f3(3), f4(3)
(3, 6, 12, 24)

So you write a function that calls the original function the number of times specified as a parameter and you pre-bind the count parameter.

Upvotes: 2

Related Questions