I want to write a function in Python that returns the multiplication of n functions (f1(x) * f2(x) * f3(x) * ... * fn(x))
.
I was thinking in something like:
def mult_func(*args):
return lambda x: args(0)(x) * args(1)(x) ...
but I don't know exactly how to loop through the n
functions in args.
Thank you.
Multiplication of Functions To multiply a function by another function, multiply their outputs. For example, if f (x) = 2x and g(x) = x + 1, then fg(3) = f (3)×g(3) = 6×4 = 24. fg(x) = 2x(x + 1) = 2x2 + x.
When you multiply two functions together, you'll get a third function as the result, and that third function will be the product of the two original functions. For example, if you multiply f(x) and g(x), their product will be h(x)=fg(x), or h(x)=f(x)g(x).
Its very simple - just use reduce:
from operator import mul
def mult_func(*args):
return lambda x: reduce(mul, (n(x) for n in args), 1)
That's just a generator expression looping through the functions, and reducing by multiplication.
args
is just a tuple, but it will be difficult to iterate over them the way you need to in a lambda
expression (unless you use reduce
). Define a nested function instead.
def mult_func(*args):
def _(x):
rv = 1
for func in args:
rv *= func(x)
return rv
return _
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 of x
.
Quick example:
def square(n):
return n**2
>>> print mult_func(2, square, square)
16
>>> print mult_func(2, square, square, square)
64
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