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.
You can define this very simply in terms of your old repeat function:
First, you've got the base case wrong:
After all,
repeat(fn, 1)
is just a function that appliesfn
once—that'sfn
.Now, if the base case is when
n == 1
, the recursive case is almost always going to be something where you passn - 1
to yourself.So, what's the difference between
repeat(fn, n)
andrepeat(fn, n-1)
? If you can't figure it out, expand a simple case out in your head or on paper:And now it's obvious:
repeat(fn, n)
is the same thing asfn(repeat(fn, n-1))
, right? So:However, as filmor points out in the comments, it would be easier to use
partial
here: