如何重复一个函数n次
我正在尝试用 python 编写一个函数,如下所示:
def repeated(f, n):
...
其中 f 是一个接受一个参数的函数,n 是一个正整数。
例如,如果我将 square 定义为:
def square(x):
return x * x
并且我称其
repeated(square, 2)(3)
为 3、2 次方。
I'm trying to write a function in python that is like:
def repeated(f, n):
...
where f
is a function that takes one argument and n
is a positive integer.
For example if I defined square as:
def square(x):
return x * x
and I called
repeated(square, 2)(3)
this would square 3, 2 times.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
应该可以做到:
输出:
或更少的 lambda ?
That should do it:
output:
or
lambda
-less?使用
reduce
和lamba。构建一个以您的参数开始的元组,后跟您要调用的所有函数:
Using
reduce
and lamba.Build a tuple starting with your parameter, followed by all functions you want to call:
像这样的东西吗?
Something like this?
使用名为
repeatfunc
的 itertools 配方来执行此操作。给出
代码
来自 itertools Recipes:
演示
可选:您可以使用第三方库,
more_itertools
,可以方便地实现这些方法:通过
> 安装pip 安装 more_itertools
Use an itertools recipe called
repeatfunc
that performs this operation.Given
Code
From itertools recipes:
Demo
Optional: You can use a third-party library,
more_itertools
, that conveniently implements these recipes:Install via
> pip install more_itertools
使用reduce和itertools.repeat(按照Marcin的建议):
您可以按如下方式使用它:(
分别导入
os
或定义square
之后)Using reduce and itertools.repeat (as Marcin suggested):
You can use it as follows:
(after importing
os
or definingsquare
respectively)我认为你想要函数组合:
I think you want function composition:
这里有一个使用
reduce
的秘诀:我称之为
power
,因为这实际上就是幂函数的作用,用组合代替了乘法。(f,)*p
创建一个长度为p
的元组,在每个索引中都填充有f
。如果您想变得更奇特,您可以使用生成器来生成这样的序列(请参阅itertools) - 但请注意它必须在 lambda 内部创建。myapply
在参数列表中定义,因此仅创建一次。Here's a recipe using
reduce
:I call this
power
, because this is literally what the power function does, with composition replacing multiplication.(f,)*p
creates a tuple of lengthp
filled withf
in every index. If you wanted to get fancy, you would use a generator to generate such a sequence (seeitertools
) - but note it would have to be created inside the lambda.myapply
is defined in the parameter list so that it is only created once.