I'm stuck at higher-order functions in python. I need to write a repeat function repeat that applies the function f n times on a given argument x.
For example, repeat(f, 3, x) is f(f(f(x))).
This is what I have:
def repeat(f,n,x):
if n==0:
return f(x)
else:
return repeat(f,n-1,x)
When I try to assert the following line:
plus = lambda x,y: repeat(lambda z:z+1,x,y)
assert plus(2,2) == 4
It gives me an AssertionError. I read about How to repeat a function n times but I need to have it done in this way and I can't figure it out...
f(x)function returning anything? Unless otherwise specified, it will returnNonef(x)?repeatreturn something likereturn f(repeat(f,n-1,x))?plus(0,2), which should be 2 but your code gives 3. It doesn't recurse, so it should be easy to debug.asserting, you can try looking at the actual return value ofplus. Try it with different inputs and it will be easy to see what the problem is.