I am trying to access the value of the lambda functions when i pass the value on the same line as the function is called. the only way i can get the value is to return(f). Is there any way to access the value before this and compare it to other values?
def func(f):
return(f)
func(lambda x: x*2)(3)
6
You can't. The (3) is passed to what func() returns, so the func can't access it. This is what happens:
def func(f):
return f # parenthesis unnecessary.
func(lambda x: x*2)(3)
Which, when the lambda function is returned, turns to:
(lambda x: x*2)(3)
Which is:
3*2 # 6
This way, you see that the function does not interact with the argument passed to the lambda. You can't access it directly.
I'm still not sure about your use case - are you trying to do something like this?
def func(f, *args):
result = f(*args)
# Do some simple comparison with the result of the lambda
myValue = 8
msg = "8 > %d" if 8>result else "8 <= %d"
return msg % result
print(func(lambda x:x*2, 3)) # prints 8 > 6
print(func(lambda x:x*2, 5)) # prints 8 <= 10
print(func(lambda x:x**2, 3)) # prints 8 <= 9
As you can see, doing that requires changing func to accept the parameter for the lambda along with the lambda itself.
Related
I'm trying to understand a solution to a problem that involves lambda functions, but I can't get just one part through my head.
Problem Statement
seven(times(five())) # must return 35
four(plus(nine())) # must return 13
eight(minus(three())) # must return 5
six(divided_by(two())) # must return 3
Requirements:
There must be a function for each number from 0 ("zero") to 9 ("nine")
There must be a function for each of the following mathematical operations: plus, minus, times, dividedBy (divided_by in Ruby and Python)
Each calculation consist of exactly one operation and two numbers
The most outer function represents the left operand, the most inner function represents the right operand
Division should be integer division. For example, this should return 2, not 2.666666...:
Solution
def zero(f = None): return 0 if not f else f(0)
def one(f = None): return 1 if not f else f(1)
def two(f = None): return 2 if not f else f(2)
def three(f = None): return 3 if not f else f(3)
def four(f = None): return 4 if not f else f(4)
def five(f = None): return 5 if not f else f(5)
def six(f = None): return 6 if not f else f(6)
def seven(f = None): return 7 if not f else f(7)
def eight(f = None): return 8 if not f else f(8)
def nine(f = None): return 9 if not f else f(9)
def plus(y): return lambda x: x+y
def minus(y): return lambda x: x-y
def times(y): return lambda x: x*y
def divided_by(y): return lambda x: x/y
My Issue
In def plus(y): return lambda x: x+y, how are both arguments passed to this function? I understand that it has something to do with "closure", but I'm not able to find any documentation that helps me understand it in this context.
For example: three(plus(one())) expands to return 3 if not plus() else plus(3).
Then, plus(3) expands to return lambda x: x + 3. Where does that x get its value from?
In def plus(y): return lambda x: x+y, how are both arguments passed to this function?
It doesn't -- or at least, plus() doesn't pass both arguments into the lambda function. plus(3) returns lambda x: x + 3 -- a function that takes in one argument and increments its argument by 3. This process is known as currying.
To address your example, three(plus(one())):
one() returns 1.
plus(one()) becomes plus(1) and returns lambda x: x + 1.
three(plus(one()) becomes three(lambda x: x + 1). three() calls the lambda function passed in with an argument of 3 and returns the resulting value. This gives a final result of 4.
I am following the Python tutorial.
def make_incrementor(n):
return lambda x: x + n
Result:
f = make_incrementor(42)
print(f(1))
43
print(type(f))
<class 'function'>
Now consider we will replace the lambda expression by a regular function
def nolambda(x):
return x
def make_incrementor(n):
return nolambda(n)
f = make_incrementor(42)
print(type(f))
<class 'int'>
In the first case it returned <class 'function'> but in the second it returned <class 'int'>
It only points to the lamba expression in the first case and do not execute it (ok, it would raise an error because of the missing argument). I could understand that but it returns an int rather than a function in the second example, so it is very strange to me. Could you explain what's going on?
In the first example, you are returning a callable (ie. the lambda function).
In the second example, you are calling the nolambda function, which means that the return value of make_incrementor will be the same value returned by nolambda.
To better understand, try looking at it like this:
def make_incrementor(n):
def some_function(x):
return x + n
return some_function
def make_incrementor(n):
some_return_value = nolambda(n)
return some_return_value
In this code, the lambda function "sees" the argument x and the variable n, which is in the lambda's closure:
def make_incrementor(n):
return lambda x: x + n
In the other example, you have made three differences, which cause different behaviour:
you placed the function nolambda outside the make_incrementor function, so it does not have the closure
in the first example, you return the function itself (i.e. the lambda, which is a function), and in the second you return the result of nolambda
the lambda returns x + n, whereas the nolambda returns just x
The following would be equivalent to the example with lambda:
def make_incrementor(n):
def nolambda(x):
return x + n
return nolambda
In the first example, where you return lambda x: x + n, you're returning a callable (i.e. anonymous function) without an invocation – the callable maps the input parameter, n, to the lambda function but does not actually get invoked. In the second, you are returning the invoked function, because you're actually calling it by using parentheses within the make_incrementor function's body.
Create a lambda function greater, which takes two arguments x and y and return x if x>y otherwise y. input value is (9,3)
greater= lambda a,b:a>b
if a>b:
print(a)
else:
return b
print(greater(a,b))
File "/code/source.py3", line 11
return b
^
SyntaxError: 'return' outside function
Even I am getting error in return statement.
I have to only get the output as value but I am getting value with True.
Use if - else in lambda:
greater = lambda a, b: a if a > b else b
and call it as:
greater(9, 13)
Problems with your code:
Your lambda function just compares two variables and returns a True / False.
You used return outside a function which is not allowed. (Btw, there is no need of explicit if - else outside lambda when you can do within).
You don't return from a lambda function.
greater = lambda a,b: a if a > b else b
print(greater(3,4))
You can use ternary operators (a if a > b else c) in lambdas but control structures require the def keyword
Also, there is no return in a lambda function
Use a ternary if in your lambda:
greater = lambda x,y: x if x>y else y
greater(1,3) # 3
greater(4,3) # 4
Small anonymous functions can be created with the lambda keyword. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression.
Read more.
Solution without using ternary expression:
greater = lambda a, b: (a, b)[a<b]
a<b returns the boolean value False if a is greater than, or equal to, b, and True if a is smaller than b. We use the boolean value (basically representing 0 or 1) as an index to the tuple (a, b) to return our desired result.
This question already has answers here:
What's the best way to return multiple values from a function? [duplicate]
(6 answers)
Closed 6 years ago.
def compose(f,g):
return lambda f: f + 1
return lambda g: g
how can I specify the order of the return statements
These are the test cases;
add1 = lambda a: a+1
this = lambda a: a
test.expect( compose(add1,this)(0) == 1 )
def compose(f1, g1):
# do something
return lambda f:f+1, lambda g:g
will return a tuple of two functions.
You can get the individual functions like this:
func1, func2 = compose(a,b)
You cannot have two return statements in a function. Once the first one is called, the second will not be reached because the function has already returned. You could, however, use a tuple to organize the output, which would look like this.
def compose(f,g):
return (lambda f: f + 1, lambda g: g)
Be careful though, because this will return the actual lambdas as the below example shows:
In [7]: def func(f, g):
...: return (lambda f: f + 1, lambda g: g)
...:
In [8]: func(0, 0)
Out[8]: (<function __main__.<lambda>>, <function __main__.<lambda>>)
Notice the types shows by line out[8]. This means that what ever variables that the function returns to will be the actual functions, not a number. To return a number, don't use lambdas, just calculate the numbers normally.
It's also worth noting, that the parameters have no effect on this function.
def compose(f,g):
return lambda f: f + 1,lambda g: g
print compose(f,g)[0]
print compose(f,g)[1]
I am to return a function such that:
add1 = make_adder(1)
add1(5)
#Result: 6
make_adder(5)(10)
#Result: 15
I currently have
def make_adder(n):
return lambda n: n+1
add1 = make_adder(1)
** Mistake noted!!*
BUT
I have another similiar question where I need to check where the numbers match each other.
def is_same(x,y):
return x == y
def make_verifier(key):
return lambda n: is_same(262010771,key )
check_password = make_verifier(262010771)
If the key is having a different number, I am supposed to get a False, but I do not get where it is wrong
I think what you want is:
def make_adder(n):
return lambda x: n + x
As far as I can see, make_adder(n) should return a function that adds n to something that calls it. But what you have done is return lambda n: n+1, which is a function that adds 1 to something that calls it.
More explanation: In the first example, add1 or make_adder(1) is a function that adds 1 to a value passed in. In the second example: make_adder(5) is a function by itself (which adds 5), and 10 is passed into this function to give 5 + 10.
make_adder by itself is a function that creates a function that adds n to a value passed in.
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
>>> class Adder(int):
... def __call__(self, number):
... return self.__class__(self + number)
...
>>> Adder(5)(10)
15
>>> Adder(5)(10)(15)
30
>>>
def is_same(x,y):
return x == y
def make_verifier(key):
return lambda n: is_same(n,key)
check_password = make_verifier(262010771)
Instead of putting in the number 262010771, you should put n to allow the flexibility to change n later in check_password(262010771), if not it'll be fixed and always be True.