Cant understand nested lambdas in this function - python

Can someone please explain to me how this nested lambdas + decorator work and what is the chronical
logic behind the output:
amp = lambda f: lambda g:lambda x:g(f(f(x)))
my_dec=amp(lambda x: "*"+x+"*")
#my_dec
def my_print(y):
print(y)
my_print("hello")

That's a tricky one:
amp is a function that takes another function f as parameter and return another funktion g taking a function x as parameter
you call amp with lambda x: "*"+x+"*", which is applied twice to the argument of the "innermost" function before passing it to the "middle" function; the result of that is your decorator my_dec
that decorator is then applied to the my_print function, making my_print the g parameter in the lambda g: ... returned by amp
finally, you pass "hello" to that decorated function, which is routed through f i.e. lambda x: "*"+x+"*" before being passed to g i.e. my_print
The whole thing becomes much clearer if you use proper def functions and longer parameter names (keeping the original g, f, and x for reference):
def amp(f_preproc):
def my_parameterized_dec(g_function):
def decorated_function(x_original_arg):
new_arg = f_preproc(f_preproc(x_original_arg))
return g_function(new_arg)
return decorated_function
return my_parameterized_dec
#amp(lambda x: "*"+x+"*")
def my_print(y):
print(y)

Related

Is there a way to have a lambda reference inside a function always return the opposite bool value?

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

Function that applies two given functions to an outside argument in Python

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

Calculate derivative for provided function, using finite difference, Python

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

Infinite recursion using lambda in python

I have a class. This class contains a function. I want to change this function in the same way every once in a while. If I use lambda I get infinite recursion. I understand why I get this, I want to find an elegant solution.
def func(s):
return 1 # some not interesting function
class cls: # a class
def __init__(self , f):
self.f = f
c = cls(func)
c.f = lambda x: c.f(x) + 1 # i want c.f to return c.f(x) + 1
print(c.f(1)) # causes infinite recursion
I don't want to do
c.f = lambda x: func(x) + 1
because I want to change c.f in the same way more than once.
The infinite recursion is happening because inside the lambda function, c.f is resolved at call-time, so it's already the "new" lambda function instead of the original function passed to cls.__init__.
You could do something like this:
c.f = lambda x, f=c.f: f(x) + 1
Since the argument default is evaluated at the time the lambda function is created, it will be the original function on the class.

Evaluating function objects from within a function in Python

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

Categories

Resources