Definition of multiplication by functions in Python?

I am trying to define multiplication by functions in Python, in pseudocode this is:

This should return a function on x if f (x), g (x)

multiply_two_functions((f(x), g(x)) = f(x) * g(x)

      

I can do it in Haskell like this:

mult :: (Num b) => (a -> b) -> (a -> b) -> (a -> b)  
mult f g = h
    where h x = (f x) * (g x)

      

You may ask why I want to do this - I have a list of functions [f] and I want to decrease them using multiplication. Again, in Haskell:

reduce_mult list = foldl mult 1 list

      

Edit: How I use it in python, for completeness:

def prod_reduce(f_list):
    def identity(x):
        return 1
    def f_mult(f, g):
        def multiplied(x):
            return f(x) * g(x)
        return multiplied
    prod = identity
    for f in f_list:
        prod = f_mult(prod, f)
    return prod

      

Does anyone have any tips for Python implementation?

+3


source to share


3 answers


Just write a function that returns a new function that returns the product of the results of other functions:



def multiply_funcs(f, g):
    def multiplied(x):
        return f(x) * g(x)
    return multiplied

      

+6


source


If you're asking how to implement a function to create a new function that multiplies the results by the objective functions, it looks something like this:

def multiply_two_functions(f, g):
    """Return a new function for e.g. h(x) == f(x) * g(x)."""
    def h(*args, **kwargs):
        return f(*args, **kwargs) * g(*args, **kwargs)
    return h

      

Note the use of *args, **kwargs

positional and keyword to handle any arguments (see, for example, What does ** (double star) and * (star) do for parameters? ); the only limitation is that any pair f

and g

must be able to handle the same arguments that would be passed to h

. Using:

>>> def f(x):
    return x + 1

>>> def g(x):
    return 2 * x

>>> h = multiply_two_functions(f, g)
>>> h(5)
60

      




If you really want to get the job done h = f * g

, you'll have to implement the class with __call__

and __mul__

:

class Func(object):

    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)

    def __mul__(self, other):
        def new_func(*args, **kwargs):
            return self(*args, **kwargs) * other(*args, **kwargs)
        return Func(new_func)

      

It can be used like this:

>>> f = Func(lambda x: x + 1)
>>> g = Func(lambda x: 2 * x)
>>> h = f * g
>>> h(5)
60

      

+6


source


You can do pretty much the same thing in Python: return a lambda that multiplies two functions.

def multiply_two_functions(f, g):
    return lambda x: f(x) * g(x)

      

Test:

def a(x):
    return 2 * x

aa = multiply_two_functions(a, a)
print(aa(0), aa(1), aa(2))

      

Output:

(0, 4, 16)

      

+5


source







All Articles