Applying Repeated Functions

I am having problems with the question that follows: Write the recursive function again. Use that takes as argument the function f of one argument and a positive integer n. The result of repeatApply is a function of one argument, which applies f to this argument n times.

So for example, we would

repeatedlyApply (lambda x: x + 1.10) (100) ==> 110

You can assume that the following function is defined. You do not have to use it, but it can help in a pretty good solution.

def compose (f, g):
    return lambda x: f (g (x))

So far i wrote this

def compose(f,g):
    return lambda x: f(g(x))

def recApply(f,n):
    for i in range(n):
        return recApply(compose(f,f), n-1)
    return f

I am wrong because using the above recApply (lambda x: x + 1.10) (100) example, I get 1124.

Help appreciate

+5
4

:

  • return for, .
  • for, . .
  • , , , .

, ?

EDIT:. :

recApply = lambda f, n: lambda x: x if n == 0 else recApply(f, n-1)(f(x))
+2

:

def recApply(func, n):
    if n > 1:
        rec_func = recApply(func, n - 1)
        return lambda x: func(rec_func(x))
    return func

:

>>>> print recApply(lambda x: x+1,10)(100)
110
+4

, lambdas:

>>> f = lambda x: x + 10
>>> iterate = lambda f, n, x : reduce(lambda x, y: f(x), range(n), x)
>>> iterate(f, 10, 3)
103
>>> iterate(f, 4, 4)
44
>>> f10 = lambda x: iterate(f, 10, x)
>>> f10(5)
105
+2

, - . , :

>>> repeatedlyApply = lambda f, n: reduce(lambda f1, f2: compose(f1, f2), [f]*n)
>>> repeatedlyApply(lambda x: x+1,10)(100)
110
0

All Articles