python - 创建一个 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 那样返回整数答案。
解决方案
你需要做的是创建一个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))
你可以在这里现场体验
推荐阅读
- c# - 2个接口的常用方法
- java - 将 Web 应用程序转换为 RESTful Web 服务
- purescript - purescript 中列表/数组中的类似记录类型
- angular - 如何清除我的 Angular 2 ng-if textarea 的值,以免它通过
- python-3.x - Python递归与改进
- r - 如何在使用 Microsoft R 的“remoteScript”执行 R 脚本时将控制台中的所有内容保存到文本文件?
- swift - (Swift) 如何使用 Segue 将 textField 传递给另一个 ViewController 下的 TableViewCell?
- java - 如何将 JComponents 放置在 Jframe 背景图像上?
- java - 找不到适合 jdbc:derby 的驱动程序
- java - 从 OpenAPI 生成 Spring MVC 映射时可以添加方法参数吗?