Suppose I have function, f
, which takes in some variable and returns a variable of the same type. For simplicity, let's say
def f(x):
return x/2+1
I'm interested in applying f
to itself over and over. Something like f(f(f(...(f(x))...)))
.
I could do this like
s = f(x)
for i in range(100):
s = f(s)
But I was wondering if there was a simpler, less verbose way to doing the same thing. I wan't to avoid for
loops (just as a challenge to myself). Is there maybe some way of using map
or a similar function to accomplish this?
Composing a Function with Itself To compose a function with itself, we simply input a function into itself using the definition of composition of functions. In other words, to compose a function, f(x) , with itself, we compute f(f(x)) f ( f ( x ) ) or (f∘f)(x) ( f ∘ f ) ( x ) .
The answer is no, if the axiom of foundation is accepted as part of set theory.
Apply functions are a family of functions in base R which allow you to repetitively perform an action on multiple chunks of data. An apply function is essentially a loop, but run faster than loops and often require less code.
Use the oml. index_apply function to run a Python function multiple times in Python engines spawned by the database environment. The times argument is an int that specifies the number of times to run the func function. The func argument is the function to run.
Is there maybe some way of using
map
or a similar function to accomplish this?
Not map
, but reduce
. I wouldn't use it for this, but you could call reduce
on an n-item sequence to cause f
to be called n times. For example:
>>> def f(x):
... return x+1
...
>>> reduce(lambda n,_: f(n), range(100), 42)
142
Explanation:
n
is assigned each successive return value of f
._
is the list of numbers from range(100)
. These numbers are all ignored. All that matters is how many there are.42
is the starting value.100
nested calls to f(f(f...(f(42))...))
results in 142
.
In Python, a for loop is the most ergonomic and readable way to do this. So I would consider this mostly an exercise — these are more natural to use in functional languages.
functools.reduce
collapses a list of values to a single value by repeatedly calling a function of two arguments. Here's factorial:
>>> import functools, operator
>>> operator.mul(2,3)
6
>>> functools.reduce(operator.mul, range(1, 10), 1)
362880
We can abuse this to use a list of values for its length only and ignore the actual contents.
>>> def f(x):
... return x/2+1
...
>>> functools.reduce(lambda x, y: f(x), range(10), 1)
1.9990234375
Or we can string together n copies of the (unary) function in a list and collapse them by applying each one to the accumulated value.
>>> import itertools
>>> functools.reduce(lambda x, g: g(x), itertools.repeat(f, 10), 1)
1.9990234375
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With