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.
Something like this?
I think you want function composition:
Here's a recipe using
reduce
:I call this
power
, because this is literally what the power function does, with composition replacing multiplication.(f,)*p
creates a tuple of lengthp
filled withf
in every index. If you wanted to get fancy, you would use a generator to generate such a sequence (seeitertools
) - but note it would have to be created inside the lambda.myapply
is defined in the parameter list so that it is only created once.That should do it:
output:
or
lambda
-less?There is an itertools recipe called
repeatfunc
that performs this operation.From itertools recipes:
I use a third-party library,
more_itertools
, that conveniently implements these recipes (optional):Using
reduce
and lamba. Build a tuple starting with your parameter, followed by all functions you want to call: