1

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.