7

I want a function named times(), in order to make:

times(func,2) equivalent to lambda x:func(func(x))

and times(func,5) equivalent to lambda x:func(func(func(func(func(x)))))

Is there such a tool in Python? What would the code looks like if I want to write it by myself?

Thanks!

0

2 Answers 2

15

I'd suggest to call this power(), since this is actually the nth power of a function. There is no such thing in the standard library, but you can easily implement it yourself:

def power(f, n):
    def wrapped(x):
        for i in range(n):
            x = f(x)
        return x
    return wrapped
Sign up to request clarification or add additional context in comments.

2 Comments

I would give this +100 if I could. So elegant!
I'm just wondering whether there's a recursive instead of iterative way to do this..
5

Thanks, Sven

I found a recursive way to do that, but yours looks more pythonic:

def power(func, n):
    def lazy(x, i=n):
        return func(lazy(x, i-1)) if i > 0 else x
    return lazy    

>>> power(lambda x:x*2,3)(9)
72
>>> power(lambda x:x*2,2)(9)
36
>>> power(lambda x:x*2,1)(9)
18
>>> power(lambda x:x*2,0)(9)
9

And a way implemented with decorator:

def powerize(n):
    def wrapped(func):
        def newfunc(*args):
            return power(func,n)(*args)
        return newfunc
    return wrapped

@powerize(3)
def double_3(x):
    return x*2

>>> double_3(8)
64

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.