Lets say we have two defined function objects
add1 = lambda x: x+1
and
square = lambda x: x*x
now I want to have a function that calls and adds the result of these two functions.
What I thought would work is:
def addFuncs(f,g):
f+g
addFuncs(add1,square)(10)
Which I thought would give me an answer of 111 (10*10 + 10+1)
But that just gave me an error TypeError: unsupported operand type(s) for +: 'function' and 'function'
So I tried:
def addFunctions(f, g):
def getf():
return f
def getg():
return g
return getf() + getg()
But still to no avail...
However, if I do
def addFunctions(f, g):
return f
it pops out with 100, so it seems to evaluate the function on return, But I can't figure out how to get it to evaluate the functions first and then operate on them.
Any help would be greatly appreciated!
EDIT
Got it!
def addFunctions(f, g):
return lambda x: f(x) + g(x)
def addFuncs(f,g):
return lambda x: f(x) + g(x)
addFuncs(add1,square)(10)
Python doesn't support adding functions together which both of your attempts tried to do. Instead, you need to create a new function, such as with lambda which calls the original functions.
Your original idea will work if you instead call these functions and then add their return values, rather than trying to add them themselves;
def addFuncs(f,g,x):
f(x) + g(x)
This is because f and g are actually LambdaTypes, and the () operator calls them, allowing the + operator to add their return values. When you use the + operator on them directly, the + operator doesn't know how to add two LambdaTypes.
EDIT
To add a little more; the reason
def addFunctions(f, g):
def getf():
return f
def getg():
return g
return getf() + getg()
doesn't work is because you are, again, trying to add together two function objects. However, your example of
def addFunctions(f, g):
return f
WILL work, because this will simply return another function object, which is then called with an argument of value 10 in your statement
addFuncs(add1,square)(10)
addFuncs takes arbitrarily many functions as input and returns a function:
def addFuncs(*funcs):
def _addFuncs(*args):
return sum(f(*args) for f in funcs)
return _addFuncs
add1 = lambda x: x+1
square = lambda x: x*x
print(addFuncs(add1,square)(10))
yields
111
Related
If I have a function that takes in a lambda reference as a parameter, and returns that reference so when it's called, it returns the value of that lambda function (boolean).
Is there a way to have it return the opposite boolean value?
def returns_diff(lambda_function):
return lambda_function
f = returns_diff(lambda x : x > 2)
f(0)
# I know I can do it this way but I want to do it inside the function.
# print(not(f(0)))
---> Should return True because it's supposed to return False since 0 is not bigger than two (return the opposite value of the lambda function)
I know I can just do: not(f(0)) when calling it, but I want to do it inside the function, not when I call it.
If you want to generate a function that returns the boolean opposite of a given function, you can do it like this:
def returns_diff(func):
return lambda x: not func(x)
f = returns_diff(lambda x: x>2)
f(0) # returns True
That's assuming the functions take one argument, as in your question. You can also make a version that works for functions with any number of positional or keyword arguments:
def returns_diff(func):
return lambda *args, **kwargs: not func(*args, **kwargs)
Can i use classes? Or it need to be just plain functions? With classes i would do
class diff:
def __init__(self,lambda_func):
self.lambda_func = lambda_func
def __call__(self,x):
return not(self.lambda_func(x))
f = diff(lambda x: x > 2)
f(0) #True
I'm learning Python right now and I am just trying to get to grips with all of the syntax options.
Currently, the only thing that I can't seem to google up is what to do if I for some reason want to define a function which contains multiple other defines.
While I understand what to do if there's only 1 define inside the the larger define (val = f()(3,4) returns 7 if you exclude the second def below), I don't know how to correctly use the function below.
If it's possible, what is the syntax for a def function with an arbitrary amount of defined functions within it?
Code:
def f():
def x(a,b):
return a + b
return x
def y(c,d):
return c + d
return y
val = f()(3,4)(5,6)
print(val)
I expected the above to return either (7,11) or 11. However, it returns 'int object is not callable'
When you write val = f()(3,4)(5,6), you want f to return a function that also returns a function; compare with the simpler multi-line call:
t1 = f()
t2 = t1(3,4)
val = t2(5,6)
The function f defines and returns also has to define and return a function that can be called with 2 arguments. So, as #jonrsharpe said, you need more nesting:
def f():
def x(a, b):
def y(c, d):
return c + d
return y
return x
Now, f() produces the function named x, and f()(3,4) produces the function named y (ignoring its arguments 3 and 4 in the process), and f()(3,4)(5,6) evaluates (ultimately) to 5 + 6.
I am given a list of functions and asked to define plus(x,y) with add1 and repeated. plus is a function that takes in two numbers and returns the total. However, I cannot get any output with my definition. It just gives the name of the function. Any help is appreciated!
add1 = lambda x: x + 1
def compose(f, g):
return lambda x: f(g(x))
def repeated(f, n):
if n == 0:
return lambda x: x
else:
return compose(f, repeated(f, n - 1))
def plus(x, y):
return repeated(add1, y)
That is an interesting way to do addition. It works quite well, you just missed one thing. Repeated returns a function which will give the sum, not the sum itself. So you just have to call repeated(add1, y) on x like this
def plus(x, y):
return repeated(add1, y)(x)
The rest of the code works fine.
The detail is that plus returns a function and that's why you see the name of the function instead of a numeric value. I think that's why there is the x parameter in plus. Just change this line of code to
return repeated(add1, y)(x)
This will evaluate the return function of repeated with the value in x.
So using
plus(5, 1)
>> 6
I'm going through some interview prep questions a college advisor gave me and this question was suggested as being prepared for different interviews:
"Complete the function:
applyFunctions(outer_function, inner_function)
which takes two functions, an outer and an inner, and returns a function which applies the outer function to the inner function to an argument."
I'm somewhat puzzled by this question, given that it does not accept the argument in the function, but instead is applied outside of it:
applyFunctions(outer_function, inner_function)(5)
I am familiar with lambda and its uses, but this question has stumped me.
Any suggestions would be great. Thank you in advance.
EDIT:
A test case (example) included is:
add2 = lambda x: x + 2
times2 = lambda x: x * 2
compose(add2,times2)(3)
> 8
First define what inner and outer are: functions that take an argument and return a result.
Then define apply, a function that takes two functions, and returns a function that combines the two in some manner.
def inner(n):
print("inner called")
return 3 * n
def outer(n):
print("outer called")
return n - 5
def apply(inn, out):
return lambda n: out(inn(n))
a = apply(inner, outer)
print(a(5))
output:
10
What they mean is: make a function that, given f and g, makes a function that takes x and gives f(g(x)). A function that takes f and g looks like lambda f,g:<something> A function that takes x is lambda x:<something>. Putting it together, you have lambda f, g: lambda x: f(g(x)).
Use lambda to create a new function that passes all of *args and **kwargs to inner_function, which returns to outer_function:
def applyFunctions(outer_function, inner_function):
return lambda *args, **kwargs: outer_function(inner_function(*args, **kwargs))
I should probably start by saying that I am relatively new to python, but I have coded in java and Matlab before.
In python, the code
def func(f):
return f
g = func(cos)
print(g(0))
gives the result
>1.0
as g now is defined as the cosine function.
I want to write a function that calculates the derivative of any provided function using a finite difference approach. The function is defined as
def derivator(f, h = 1e-8):
and would like to achieve the follwing:
g = derivator(cos)
print(g(0)) # should be about 0
print(g(pi/2)) # should be about -1
At the moment my derivator function looks like this
def derivator(f, h = 1e-8):
return (f(x+h/2)-f(x-h/2))/h
which definitely is wrong, but I am not sure how I should fix it. Any thoughts?
Your current derivator() function (which should probably be called differentiator()) uses an undefined variable x and would return a single value, if x were defined--the value of f'(x). You want to return a function that takes an x value. You can define an inner function and return it:
def fprime(x):
return (f(x+h/2)-f(x-h/2))/h
return fprime
Because you don't use that function anywhere else, though, you can use lambda instead, which is also shorter:
return lambda x: (f(x+h/2)-f(x-h/2))/h
The only thing PEP 8 says about lambdas is that you should not assign the result of the lambda to a variable, then return it:
fprime = lambda x: (f(x+h/2)-f(x-h/2))/h # Don't do this!
return fprime
Make an inner function inside your derivator function and return it:
from math import cos, pi
def derivator(f, h = 1e-8):
def g(x):
return (f(x+h/2)-f(x-h/2))/h
return g
g = derivator(cos)
print(g(0)) # 0.0
print(g(pi/2)) # -0.999999993923
f and h will be part of the closure of the returned function.
You can also return a lambda expression to make it one line:
return lambda x: (f(x+h/2)-f(x-h/2))/h