Can anyone explain, how this peice of code works? - python

def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
The value of n = 2, after that I'm confused what is the value of a, and how the lambda function is executed.

Your myfunc is a nested function, lambdas are functions.
An equal implementation would be:
def outer(n):
def inner(a):
return a * n
return inner
Which returns a function like your original myfunc as well. Since the return of the call of myfunc is also a function, you may well call the inner function as well.

When the outer function is called, the inner lambda creates a function. The outer lambda then returns the called function.It happens that describe above..i.e: when we call mydoubler(11),given the value a=11 and call n=2.

Related

Double numbers in Python using Lambda

I am trying to double numbers using Lambda function in python but can't understand the function that's all because I'm starting to learn python. Below is the function:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
I just need to understand how this code is working. Any help will be much appreciated.
def myfunc(n): # this function is taking input n and returning a function object
return lambda a : a * n # this function is taking input as a and we are returning this function object
mydoubler = myfunc(2) # now we are calling the returned function object if you print(mydoubler)-> this will give you function object
print(mydoubler(11)) # here we are calling the lambda function with parameters
If you want to implement it without lambda then you can use partial
from functools import partial
def double(n, a):
return a * n
def my_func1(n):
return partial(double,n)
mydoubler = my_func1(2)
print(mydoubler(11))
Your myfunc function creates and returns a closure. In this case, it returns a function that returns its argument times n. The tricky part is that n refers to the value in the specific call frame for myfunc. In your example, n has the value 2. That instance of n is specific to that particular call to myfunc. So if you called myfunc several times in a row, with several different values for n, each of the returned lambda functions would refer to a unique value of n unrelated to the other values.
Note that the use of lambda is optional. It's just shorthand for an anonymous function. For example, you could have written myfunc as:
def myfunc(n):
def f(a):
return a * n
return f
which would produce the same result.
Back to the original question, here's an example of multiple closures coexisting:
def myfunc(n):
def f(a):
return a * n
return f
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
This prints 22 followed by 33. This works because mydoubler and mytripler each refer to different instances of n.
The value of n can even be modified by calls to the returned closure. For example:
def myfunc(n):
def f(a):
nonlocal n
n += a
return n
return f
func = myfunc(100)
print(func(1))
print(func(5))
This prints 101 followed by 106. In this example, the nonlocal declaration is needed since f assigns to n. Without it, n would be taken to be local to f.

How can I call a lambda without defining it as a function?

For lambda functions in the following code,
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
I am trying to understand why mydoubler becomes <class 'function'> and how I can call mydoubler(11) without defining it as a function.
A lambda is a function, but with only one expression (line of code).
That expression is executed when the function is called, and the result is returned.
So the equivalent of this lambda:
double = lambda x: x * 2
is this def function:
def double(x):
return x * 2
You can read more here
A lambda is a function, so your code is doing something like
def myfunc(n):
def result(a):
return a * n
return result # returns a function
mydoubler = myfunc(2)
print(f(11))
You're asking how to call mydoubler without defining it as a function, which isn't the clearest question, but you can call it without naming it like so
print( myfunc(2)(11) )
Your myfunc is returning a lambda. Lambda is a small anonymous function. A lambda can take any number of arguments, but can only have one expression.
So after execution of the 3rd line, your mydoubler will become a lambda that's why when you try print(type(mydoubler)) it will return <class 'function'>.
Also in order to call mydoubler with 11, it must be function.
A lambda expression, like a def statement, defines functions. Your code could be equivalently written as
def myfunc(n):
def _(a):
return a * n
return _
mydoubler = myfunc(2)
print(mydoubler(11))
Because the inner function is simple enough to be defined as a single expression, using a lambda expression saves you the trouble of coming up with the otherwise unused name the def statement requires.
The key here is that the inner function closes over the value of n, so that the function returned by myfunc retains a reference to the value of the argument passed to myfunc. That is, mydoubler is hard-coded to multiply its argument by 2, rather than whatever value n may get later. (Indeed, the purpose of the closure is to create a new variable n used by the inner function, one which cannot easily be changed from outside myfunc.)
using decorator you can achive this
from functools import wraps
def decorator_func_with_args(arg1):
def decorator(f):
#wraps(f)
def wrapper(val):
result = f(val)
return result(arg1)
return wrapper
return decorator
#decorator_func_with_args(arg1=2)
def myfunc(n):
return lambda arg:arg*n
result = myfunc(1211)
print(result)
output
2422
Do you mean this?
mydoubler = lambda a : a * 2
mydoubler(11)

Error using np.vectorize inside a function

I am trying to create a function called function2 that vectorize a function, it works when I only create one function, but if try to wrap it in another function I dont get the results that I need
this code works
A= np.array([1])
B= np.array([2])
def function1(a, b):
if a > b:
return a - b
else:
return a + b
function1 = np.vectorize(function1)
function1(A, B)
out array([3])
but this one does not and I dont know why, I am expecting to get the same result as the code above array([3])
def function1(a, b):
if a > b:
return a - b
else:
return a + b
def function2(a, b):
function2 = np.vectorize(function1)
return function2
function2(A, B)
out <numpy.vectorize at 0x24f0a22eba8>
thanks for the help in advance
That is because in the second case you are not calling the function you are just returning the function object. np.vectorise returns the function object but doesn’t call it.
Change your code to -
def function3(a, b):
function2 = np.vectorize(function1)
return function2(a,b) #call here
function3(A,B)
Should work now.
In the first case function2 is the vectorised function object itself and passing (A,B) parameters to it will call it.
In second case function2 is a parametric function but instead of using the parameters a,b it simple returns a function object. So when you call it with parameters, it overwrites function2 and returns a vectorised function object each time, completely ignoring the parameters all together.
In the third case (my solution) you are calling function3 which takes A,B parameters and first vectorises function1. Next it calls this vectorised function with the passed parameters and returns the output.
Follow the function calls and the sequential lines of code in your function and it will be super clear of why that is happening.

Returning Nested Functions in Python

def raise_val(n):
"""Return the inner function."""
def inner(x):
"""Raise x to the power of n."""
raised = x ** n
return raised
return inner
square = raise_val(2)
cube = raise_val(3)
print(square(2), cube(4))
Outputs:
4 64
Can anybody explain to me how come square(2) knows that the argument passed is x?
this code uses the concept of lexical closures or closures.Closures are the function that remembers the parameters passed to their parent function.The more technical definition will be,Closures are the function that remembers values in enclosing scope even if they are not actually present in the memory.
#for example`
def outer(x):
def inner():
print(f"The argument passed to outer was {x}")
'''Notice how inner() will grab the argument passed to the outer function'''
return inner
value=outer(69)
print(value())
Maybe this will help: https://stackabuse.com/python-nested-functions/
Notice you "sends arguments twice" (not really): first in square = raise_val(2) and second in square(2). What happens? The first calls return a function: you call to raise_val and it returns inner, which is a function. Now square variable actually holds a function. Second call, square(2), just call to the function.
It's the same as:
def a(x):
print(x)
square = a
print(square(5))
In this example, square holds a function. It's the same as in your code, since raise_val returns a function. Square holds inner method, and later it is been called. You send x directly: square(2) sends 2 for x of course.
A more interesting can be "how inner remembers n?", and as others mentioned in comments: it's manages variables of current scope.

python calling function twice one after another but second storing value from first

I am using python so can someone tell me how to call same function twice in python but when you call it the second time it should be changed an already have value stored in it when you called the function the first time, so I basically mean you are calling the function first time and right after that you are calling it again but with the return value from the first time you called that function.
Assuming you have a function that has both a parameter and a return value:
def myFunction(input):
# do something with input
return input
To have a second instance of the function use the result of the first instance, you can simply nest the functions:
result = myFunction(myFunction(value))
you can create function that will apply n-times
def multf(f, n, x):
if n == 0:
return x
return multf(f, n-1, f(x))
so here we apply lambda sqr 3 times, it becomes f(f(f(x)))
sqr = lambda x: x**2
print(multf(sqr,3,2))
256

Categories