Python:编写函数的 n 个组合的更好方法?

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)

Tim*_*ers 5

如果您追求速度,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)

  • 啊啊我喜欢这个。直到今天早上我才学会递归。我没有研究你的解决方案,因为我不想为自己破坏任何东西。我用递归回答了我原来的问题,它看起来与你的几乎相同!谢谢! (2认同)