本文介绍了如何重复n次功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在python中编写一个函数,例如:
I'm trying to write a function in python that is like:
def repeated(f, n): ...其中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我打电话
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少?
def repeated(f, n): def rfun(p): acc = p for _ in xrange(n): acc = f(acc) return acc return rfun更多推荐
如何重复n次功能
发布评论