Multiplication of n functions

I want to write a function in Python that returns the multiplication of n functions (f1(x) * f2(x) * f3(x) * ... * fn(x)) .

I thought in something like:

 def mult_func(*args): return lambda x: args(0)(x) * args(1)(x) ... 

but I don’t know exactly how to iterate over n functions in args.

Thanks.

+6
source share
4 answers

Its very simple - just use the shortcut:

 from operator import mul def mult_func(*args): return lambda x: reduce(mul, (n(x) for n in args), 1) 

It is simply an expression of a generator passing through functions, and reduction by multiplication.

+6
source

args is just a tuple, but it will be difficult to iterate over them as you need in the lambda expression (unless you use reduce ). Define a nested function.

 def mult_func(*args): def _(x): rv = 1 for func in args: rv *= func(x) return rv return _ 
+5
source
 def mult_func(x, *args): total = 1 for func in args: total *= func(x) return total 

Very simply returns the product of all args with input x .

Quick example:

 def square(n): return n**2 >>> print mult_func(2, square, square) 16 >>> print mult_func(2, square, square, square) 64 
+2
source

This is the time of night, so here is a mutually recursive solution:

 def multiply_funcs(funcs): def inner(x): if not funcs: return 1 return funcs[0](x) * multiply_funcs(funcs[1:])(x) return inner 
0
source

Source: https://habr.com/ru/post/987097/


All Articles