Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
 square(9)
 square(81)
 square(6561)
 square(43046721)
 1853020188851841

or lambda-less?

def repeated(f, n):
    def rfun(p):
        acc = p
        for _ in xrange(n):
            acc = f(acc)
        return acc
    return rfun

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...