Reputation: 47061
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!
Upvotes: 7
Views: 182
Reputation: 47061
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
Upvotes: 5
Reputation: 601569
I'd suggest to call this power()
, since this is actually the n
th 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
Upvotes: 15