I have a function that does some calculation, g (x). Now I want to write a function that computes g (g (g (... g (x)))), where g is applied n times. I tried to do this using repeat_fn(see below), but this will not work.
According to a Recursive function using a lambda expression , the solution is to use functools.partial. It really works, but I don’t understand how to do it. Also, I don't understand why my approach is not working.
g = lambda x: 2*x
def repeat_fn(f, n):
if n == 1:
return f
else:
return lambda y: f( repeat_fn(f(y), n-1) )
def repeat_fn_base(fn, n, x):
if n == 1:
return fn(x)
else:
return fn(repeat_fn_base(fn, n-1, x))
def repeat_fn2(fn, n):
return functools.partial(repeat_fn_base, fn, n)
j = repeat_fn2(g, 5)
print(type(j))
print(j(2))
k = repeat_fn(g, 5)
print(type(k))
print(k(2))
, repeat_fn , k = repeat_fn(g, 5), , . -, , k . print(k(2)) : TypeError: unsupported operand type(s) for *: 'int' and 'function'.
, , , h = g(g(x) .
- ? !