0

Thank you guys. I find I cannot post my question on internet.

However, it is really helpful to me.

2
  • 1
    Is there any code you can show? Commented Oct 7, 2015 at 2:35
  • 3
    I sense an XY Problem. Commented Oct 7, 2015 at 2:37

4 Answers 4

5

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.