I need to create a recursive function repeat which takes in a function and uses the function n number of times with the value of x. Here's an iterative version that explains my issue a bit more in 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 it can work like this.
square_three_times = repeat(lambda x: x**2, 3)
print(square_three_times(3)) return 6561
I have tried something like this but im really lost and 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 wouldnt work since the recursion would keep going forever. But im not sure how i should write this code since i first need to calculate 3^2 before taking the next step 9^2 and so on.