Daniel Wesley Porteous Daniel Wesley Porteous - 1 year ago 70
Python Question

Python: Returning a function that runs a given function n times

I'm trying to write a function that takes a function as its argument and returns a new function that runs said function a given number of times.

For example, if I had a function:

def doubleNumber(num):
return num * 2

and I did the following:

doubleThrice = repeatFunction(doubleNumber, 3)

I should then get this:

doubleThrice(3) # Returns 18 but should it?

I have this so far, but I don't think it's doing what I want:

def repeatFunction(func, n):
def inner(inp):
return func(inp) * n
return inner

I get the impression that it is just running the function once and then multiplying the result by n, not running the function n times, though I'm not sure.

I just can't think of how to build the function I need inside the repeatFunction function and return it, nor has any of the online help really made sense to me.

Answer Source

If you want to apply a function several times, you probably need a loop that repeats that many times:

def repeatFunction(func, n):
    def inner(inp):
        for i in range(n):
            inp = func(inp)
        return inp
    return inner
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download