Han*_*Sun 7 python recursion functional-programming function
我想要一个名为的函数times(),以便:
times(func,2) 相当于 lambda x:func(func(x))
和times(func,5)相当于lambda x:func(func(func(func(func(x)))))
Python中有这样的工具吗?如果我想自己编写代码,代码会是什么样的?
谢谢!
Sve*_*ach 15
我建议称之为power(),因为这实际上n是函数的强大功能.标准库中没有这样的东西,但您可以自己轻松实现它:
def power(f, n):
def wrapped(x):
for i in range(n):
x = f(x)
return x
return wrapped
Run Code Online (Sandbox Code Playgroud)
谢谢,斯文
我发现了一种递归方式,但是你看起来更加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
Run Code Online (Sandbox Code Playgroud)
以及使用装饰器实现的方法:
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
Run Code Online (Sandbox Code Playgroud)