Reputation: 41
Thank you guys. I find I cannot post my question on internet.
However, it is really helpful to me.
Upvotes: 0
Views: 289
Reputation: 531265
While this can be implemented concisely using recursion, an iterative solution is more efficient and won't break for large values of n
.
def compose(f, n):
def iterated_f(x):
rv = x
while n > 0:
rv = f(rv)
return rv
return iterated_f
Upvotes: 0
Reputation: 5261
Compose will need 3 arguments: the function to compose, the number of times to compose it, and the initial argument. So if you want to evaluate f(f(f(7))) you would call compose(f, 3, 7).
def compose(f, n, x):
if n == 0: return x
return compose(f, n-1, f(x))
It's occurred to me that maybe this isn't exactly what you want. Perhaps you want to be able to write g = compose(f, 3)
and then call g(7)
. This requires only a minor modification:
def compose(g, m):
def composer(f, n, x):
if n == 0: return x
return compose(f, n-1, f(x))
return lambda x: composer(g, m, x)
Upvotes: 5
Reputation: 5658
use saulspatz's compose and a lambda
cubed = lambda x: x**3
def compose(f, n, x):
if n == 0: return x
return compose(f, n-1, f(x))
print(compose(cubed,2,2))
512
Upvotes: 0
Reputation: 1290
I am not sure if I understand correctly, but I believe you expect compose() to return a function. In that case, this would work:
def compose(f, n):
def composed_f(x):
result = x
for i in range(n):
result = f(result)
return result
return composed_f
So, if you write:
a = compose((lambda x:x*2), 5)
print a(1)
You will get 32
Upvotes: 1