我正在尝试用 python 编写一个函数,如下所示:
def repeated(f, n):
...
其中 f
是一个接受一个参数的函数,n
是一个正整数。
例如,如果我将正方形定义为:
def square(x):
return x * x
我打电话
repeated(square, 2)(3)
这将是 3、2 的平方。
最佳答案
应该这样做:
def repeated(f, n):
def rfun(p):
return reduce(lambda x, _: f(x), xrange(n), p)
return rfun
def square(x):
print "square(%d)" % x
return x * x
print repeated(square, 5)(3)
输出:
square(3)
square(9)
square(81)
square(6561)
square(43046721)
1853020188851841
或 lambda
-less?
def repeated(f, n):
def rfun(p):
acc = p
for _ in xrange(n):
acc = f(acc)
return acc
return rfun
关于python - 如何重复一个函数n次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7359828/