How to repeat a function n times
问题 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. 回答1: That should do it: 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) output: square(3)