Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutiplication 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 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.

like image 203
Guilherme Stoll Toaldo Avatar asked May 13 '15 01:05

Guilherme Stoll Toaldo


People also ask

What is the formula for the multiplication of functions?

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.

What happens when you multiply two functions?

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).


3 Answers

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.

like image 195
Maltysen Avatar answered Oct 23 '22 12:10

Maltysen


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 _
like image 36
chepner Avatar answered Oct 23 '22 11:10

chepner


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
like image 30
David Greydanus Avatar answered Oct 23 '22 11:10

David Greydanus