Thank you guys. I find I cannot post my question on internet.
However, it is really helpful to me.
Thank you guys. I find I cannot post my question on internet.
However, it is really helpful to me.
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)
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