Question: 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.

Answer: 
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

```
Use an itertools recipe called `repeatfunc` that performs this operation.

**Given**

```
def square(x):
    """Return the square of a value."""
    return x * x

```

**Code**

From [itertools recipes](https://docs.python.org/3/library/itertools.html#itertools-recipes):

```
def repeatfunc(func, times=None, *args):
    """Repeat calls to func with specified arguments.

    Example:  repeatfunc(random.random)
    """
    if times is None:
        return starmap(func, repeat(args))
    return starmap(func, repeat(args, times))

```

**Demo**

Optional: You can use a third-party library, [`more_itertools`](https://github.com/erikrose/more-itertools), that conveniently implements these recipes:

```
import more_itertools as mit

list(mit.repeatfunc(square, 2, 3))
# [9, 9]

```

Install via `> pip install more_itertools`