首页 > 解决方案 > 创建一个 new_function,它有一个输入 n 和一个 input_function,它返回一个 output_function,它执行 input_function 的 n 次

问题描述

我想创建一个具有两个输入 (n, input_function) 的新函数,它返回一个新的 output_function,它执行 input_function 的功能,但它执行 n 次。这是我想要完成的图像

def repeat_function(n, function, input_number):
    for i in range(n):
        input_number = function(input_number)
    return input_number

def times_three(x):
    return x * 3

print(repeat_function(3, times_three, 10))  #prints 270 so it's correct
print(times_three(times_three(times_three(10))))  #prints 270 so it's correct

#This function does not work
def new_repeat_function(n, function):
    result = lambda x : function(x)
    for i in range(n-1):
        result = lambda x : function(result(x))
    return result

new_function = new_repeat_function(3, times_three)
#I want new_function = lambda x : times_three(times_three(times_three(x))) 
print(new_function(10)) # should return 270 but does not work

我尽力实现它,但它不起作用。我需要 new_repeat_function 来做 repeat_function 所做的事情,但是 new_repeat_function 必须返回 time_three() n 次,而不是像 repeat_function 那样返回整数答案。

标签: pythonpython-3.xfunctional-programminghigher-order-functions

解决方案


你需要做的是创建一个function构建另一个function的,在python中这个模式被称为decorators,这里有一个例子:

from functools import wraps

def repeated(n):
  def wrapped(f):
    @wraps(f)
    def ret_f(*args, **kwargs):
      res = f(*args, **kwargs)
      for _ in range(1, n):
        res = f(res)
      return res
    return ret_f
  return wrapped

@repeated(2)
def times_three(x):
    return x * 3

print(times_three(10))

你可以在这里现场体验


推荐阅读