Recursive function using lambda expression

I need to create a recursive repetition of a function that takes a function and uses the function n number of times with the value x. Here is an iterative version that explains my problem in a bit more detail.

def repeat(fn, n, x):
    res = x
    for i in range(n):
        res = fn(res)
        print(res)
    return res

print(repeat(lambda x: x**2, 3, 3)) returns 6561

First it takes 3 ^ 2, then 3 ^ 2 ^ 2, which is 81, then again 3 ^ 2 ^ 2 ^ 2 = 6561. How can I make this recursive so that it can work as follows.

square_three_times = repeat(lambda x: x**2, 3)
print(square_three_times(3)) return 6561

I tried something like this, but I really lost and am not sure what to do.

def repeat(fn, n):
    if n == 1:
        return fn(n):
    else:
        def result(x):
            return fn(n)
    return repeat(fn,result(x))

This obviously won't work, as the recursion will go on forever. But I'm not sure how I should write this code, since I need to calculate 3 ^ 2 first before doing the next step 9 ^ 2, etc.

+1
2

-, :

if n == 1:
    return fn

, repeat(fn, 1) - , fn - fn.

, n == 1, , n - 1 .

, repeat(fn, n) repeat(fn, n-1)? , :

repeat(fn, 3)(x): fn(fn(fn(x)))
repeat(fn, 2)(x): fn(fn(x))

: repeat(fn, n) - , fn(repeat(fn, n-1)), ? :

else:
    def new_fn(x):
        return fn(repeat(fn, n-1)(x))
    return new_fn

, , partial :

def repeat3(fn, n, x):
    if n == 1:
        return fn(x)
    else:
        return fn(repeat3(fn, n-1, x))

def repeat(fn, n):
    return functools.partial(repeat3, fn, n)
+4

:

repeat_new = lambda fn, n: lambda x: repeat(fn, n, x)

square_three_times = repeat_new (lambda x: x**2, 3)
print(square_three_times(3))
-1

All Articles