Home > Software engineering >  How to define a function which returns sum of functions?
How to define a function which returns sum of functions?

Time:10-04

I want to define a function which returns the sum of functions' calls in Python.

The important thing is it will return another function, and not a value.

For example:

def sum_of_functions(func1, func2):
    output = func1   func2
    return output

f1 = lambda x: x**2
f2 = lambda x: x

sum_functions = sum_of_functions(f1, f2)
type(sum_functions)
# function

sum_functions(2)
# 6

Of course, is unsupported for functions, so it doesn't work.

CodePudding user response:

Return a wrapping function or lambda:

def sum_of_functions(func1, func2):
    return lambda x: func1(x)   func2(x)

Then you can call it directly or store it in a varialble:

f1 = lambda x: x**2
f2 = lambda x: x

composed = sum_of_functions(f1, f2)
assert composed(2) == sum_of_functions(f1, f2)(2)

CodePudding user response:

Something like this?

def sum_functions(func1, func2):
    def inner(x):
        return func1(x)   func2(x)
    return inner

f1 = lambda x: x**2
f2 = lambda x: x

sum_of_functions = sum_functions(f1, f2)

type(sum_of_functions)
function

sum_of_functions(2)
6

CodePudding user response:

Just go on using lambda expressions! Pass the bounded variable into the two functions, sum them together, and return the lambda expression as a whole.

Define it as follows:

def sum_of_functions(func1, func2):
    return lambda x: func1(x)   func2(x)

By the way, as far as I understand, what you really want calling sum_of_functions should be

>>> func1 = lambda x: x ** 2
>>> func2 = lambda x: x
>>> ans = sum_of_functions(func1, func2)
>>> type(ans)
function
>>> ans(2)
6

right?

  • Related