awa*_*lll 3 python function composition
我写了一个函数“rep”,它接受一个函数 f 并接受 f 的 n 个组合。所以rep(square,3)的行为如下:square(square(square(x)))。当我将 3 传递给它时,rep(square,3)(3)=6561。
我的代码没有问题,但我想知道是否有一种方法可以使其“更漂亮”(或更短),而不必调用另一个函数或导入任何内容。谢谢!
def compose1(f, g):
"""Return a function h, such that h(x) = f(g(x))."""
def h(x):
return f(g(x))
return h
def rep(f,n):
newfunc = f
count=1
while count < n:
newfunc = compose1(f,newfunc)
count+=1
return newfunc
Run Code Online (Sandbox Code Playgroud)
如果您追求速度,for循环显然是最佳选择。但如果您正在寻求理论上的学术认可;-),请坚持使用简洁的功能性习语。喜欢:
def rep(f, n):
return f if n == 1 else lambda x: f(rep(f, n-1)(x))
Run Code Online (Sandbox Code Playgroud)