我如何将函数应用n次? [英] how do I apply a function n times?
本文介绍了我如何将函数应用n次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试实现一个将要采用的高阶函数,但并没有取得太大的成功.repeat(f,n)其中,f是另一个函数,n是表示将n应用于变量x的次数的整数值.例如:
I have been trying without much success to implement a higher order function that would take in repeat(f, n) where f is another function and n is the integer value that says how many times n will be applied to a variable x. For example:
def integer(x):
x + 1
所以我将重复(integer,5)并且我将使用integer(integer(integer(integer(integer(x)
so i would have repeat (integer, 5) and I would have integer(integer(integer(integer(integer(x)
推荐答案
嗯,有一种迭代方法:
def repeat(f, n):
def new_fn(x):
for _ in range(n):
x = f(x)
return x
return new_fn
higher_fn = repeat(lambda x: x+3, 5)
higher_fn(2) # => 17 == (((((2 + 3) + 3) + 3) + 3) + 3)
和组成方法:
def repeat(f, n):
new_fn_str = "lambda x: {}x{}".format("f(" * n, ")" * n)
new_fn = eval(new_fn_str, {"f": f})
return new_fn
结果完全相同,但可能会更快.
which results in exactly the same thing but may be slightly faster.
这篇关于我如何将函数应用n次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文