Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute a chain of functions in python

I want to get the result of a chain of computations from an initial value. I'm actually using the following code:

def function_composition(function_list, origin):
    destination = origin
    for func in function_list:
        destination = func(destination)
    return destination

With each function in function_list having a single argument.

I'd like to know if there is a similar function in python standard library or a better way (example: using lambdas) to do this.

like image 932
rob Avatar asked Jun 15 '13 10:06

rob


People also ask

How do you chain multiple functions in Python?

As input, you use the result of f2(...) . As input for this function, you use the result of f1() . This way, you can chain three or more functions by using the pattern f3(f2(f1())) .

What does __ call __ do in Python?

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.


Video Answer


1 Answers

Fold while calling.

destination = reduce((lambda x, y: y(x)), function_list, origin)
like image 71
Ignacio Vazquez-Abrams Avatar answered Oct 28 '22 07:10

Ignacio Vazquez-Abrams