创建一个 new_function 有一个输入 n 和 input_function 其中 return 一个 output_function 做 input_function 做 n 次

Create a new_function which has an input n and input_function which return a output_function that does what input_function does n times

我想创建一个具有两个输入 (n, input_function) 的新函数,其中 return 是一个新的 output_function,其作用与 input_function 相同,但它做了 n 次。 Here is the image of what i'm trying to accomplish

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 做的事情,但不是像 repeat_function 那样 returning 和整数答案,new_repeat_function 必须 return time_three() n次.

你需要做的是创建一个 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))

你可以试试live here

您需要return一个函数,而不是结果。

def new_repeat_function(n, function):
    def repeat_fn(x):
        result = function(x)
        for i in range(n - 1):
            result = function(result)
        return result

    return repeat_fn

在这里,您构造一个捕获参数 nfunction 的闭包。稍后,当您调用 returned 闭包时,它会使用传递给 new_repeat_functionnfunction。所以,如果我们调用

new_func = new_repeat_function(3, three_times)
print(new_func(10))

我们得到了预期的 270。

您可以简单地重复 repeat 本身。也就是说,您根本不需要创建 range 或使用循环

def repeat (n, f):
  return lambda x: \
    x if n is 0 else repeat (n - 1, f) (f (x))

def times_three (x):
    return x * 3

new_func = repeat (3, times_three)

print (new_func (10))
# 270

您也可以跳过中间作业

print (repeat (0, times_three) (10))
# 10

print (repeat (1, times_three) (10))
# 30

print (repeat (2, times_three) (10))
# 90