【问题标题】:Creating function: (f, n) which return f(f(f( .... x... ))) n times [duplicate]创建函数: (f, n) 返回 f(f(f( .... x... ))) n 次 [重复]
【发布时间】:2018-05-31 02:18:08
【问题描述】:

我在 python 中创建一个高阶函数时遇到问题,该函数应用函数 f,n 次以生成一个新函数 h,作为其返回值。

def compile(f, n)
    # h is a function, f applied n times
    ...
    return h

new = compile(lambda x: 2*x, 3)
new(4) == 32 # new(4) == 2(2(2(4)))

【问题讨论】:

  • 请阅读How to Ask
  • 与您的问题无关:compile 是 Python 内置函数,因此您可能不应该使用该名称编写自己的函数。这样做会掩盖内置函数(如果你想使用原始的compile,可能会导致尴尬的错误)。

标签: python function recursion function-composition


【解决方案1】:

由于 Python 的函数是一等公民,因此函数本身可以定义一个新函数并返回它。在函数内部定义函数可以使用def 完成,就像在您的顶级范围内一样。

作为旁注,我建议您不要使用 compile 作为函数名称,因为它不能准确反映您要执行的操作,这称为 函数组合,以及覆盖内置函数compile

def compose_with_self(f, n):
    def composed(arg):
        for _ in range(n):
            arg = f(arg)
        return arg
    return composed

例子:

def add_one(x):
    return x + 1

add_three = compose_with_self(add_one, 3)

print(add_three(1)) # 4

【讨论】:

    【解决方案2】:

    您可以使用递归轻松做到这一点

    • 如果n 为零,则直接返回x
    • 否则n至少为1,将f(x)应用于递归结果compile (f, n - 1)

    我们可以很容易地用 Python 编码

    def compile (f, n):
      return lambda x: \
        x if n is 0 else compile (f, n - 1) (f (x))
    
    double_thrice = compile (lambda x: 2 * x, 3)
    
    print (double_thrice (4))
    # 32
    

    【讨论】:

      猜你喜欢
      • 2015-08-13
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      • 2012-09-29
      相关资源
      最近更新 更多