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.
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.
So I'm making a simple program that gets 2 functions(a and k) and one integer value(b), then it gets the formal parameter in the two functions(a and k) which is "x" and applies a condition x < b then based on the condition makes a function call, either a or b. But when I run the program it gives an error that x is not defined in the global frame. I want it to get "x" from the formal parameter assigned to the functions a and b and then get the condition based on that.
Here's my code
def square(x):
return x * x
def increment(x):
return x + 1
def piecewise(a, k, b):
if x<b:
return a
else:
return k
mak = piecewise(increment,square ,3 )
print(mak(1))
I guess you want to do something like this:
def piecewise(a, k, b):
def f(x):
if x < b:
return a(x)
else:
return k(x)
return f
However, I am not sure if it is a good practice. So, I leave my answer here to see the comments and learn if there is any problem with it.
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.
There are two examples.
# 1st example
>>> def accum(sum, a):
return sum + a
>>> sum = 0
>>> for sum in iter(lambda:accum(sum, 2), 40):
print sum,
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32...
# 2nd example
>>> def accum(sum, a):
return sum + a
>>> sum = 0
>>> for sum in iter(accum(sum, 2), 40):
print sum,
TypeError: iter(v, w) : v must be callable
Why lambda function doesn't make error but accum function makes error?
Thanks in advance :)
In neither case you are passing a function that takes arguments. In second case the value of v is bound to the integer 2, whereas in the first case v refers to a callable anonymous lambda function () -> sum + a.
The following 2 are almost equivalent:
def x():
return sum + a
x = lambda: sum + a
except lambda does not provide nice debugging traceback, since lambda functions are unnamed.
Also, the names of the variables are a bit misleading, took me a some moments to figure out what is happening. There are exactly 2 variables called sum - the one within accum function, and the other in the global scope. There is also the 3rd, masked one that contains the global built-in function sum...
The lambda is an anonymous function and is callable. If the notation is confusing, you can replace it with a named function:
def wrapper():
return accum(sum, 2)
for sum in iter(wrapper, 40):
The v argument must be callable. The result of accum(sum, 2) is an integer, which isn't callable.
I am studying the properties of functions in Python and I came across an exercise that asks to:
Write a function which returns de power of a number. Conditions: The function may only take 1 argument and must use another function to return the value of the power of a given number.
The code that solves this exercise is:
def power(x):
return lambda y: y**x
For example, if we would like to know the value of the power: 2^3, we would call the function like this: power(3)(2)
Here is what I would like to know:
Is there any way to write a function that, when called, has a similar structure: function()()().
In other words, is it possible to write a function, that requires three or more parentheses ()()() when called?
If it is possible, could you please give me an example code of that function and briefly explain it?
Also:
def power(x):
def power_extra(y):
return y
def power_another(z):
return z
return power_extra and power_another
Possible?
Sure you can:
def power_times(k):
"""use as power_times(k)(x)(y) => k * y^x"""
return lambda x: lambda y: k * y**x
print power_times(2)(3)(4) # returns 2 * 4^3 = 128
When you call this function with argument 2 (power_times(2)), it returns a lambda function that works like lambda x: lambda y: 2 * y ** x (that is, like your original function, only with an extra "times 2").
You can stack as many lambdas on top of each other as you like:
def many_lambdas(x):
"""many_lambdas(x)(y)(z)(q) => x + y * z^q"""
return lambda y: lambda z: lambda q: x + y * z ** q
print many_lambdas(1)(2)(3)(4) # prints 163
Indeed, it might be even clearer if you skipped using def at all, and just wrote:
many_lambdas = lambda x: lambda y: lambda z: lambda q: x + y * z ** q
Or, alternatively, you could skip using lambda ever and just use them as nested functions:
def many_funcs(x):
def many_funcs_y(y):
def many_funcs_z(z):
def many_funcs_q(q):
return x + y * z ** q
return many_funcs_q
return many_funcs_z
return many_funcs_y
print many_funcs(1)(2)(3)(4) # prints 163
#David's answer would aptly answer you question for fixed nested function calls. For undefined nesting, you may want to define a class and overload the __call__ method along with __repr__ and __int__ to serve your Purpose.
>>> class Power(object):
def __init__(self, value):
self.value = value
def __call__(self, value):
self.value **= value
return self
def __int__(self):
return self.value
def __repr__(self):
return str(self.value)
>>> print Power(2)(2)(2)(2)(2)
65536
>>> int(Power(2)(2)(2)(2)(2)) / 2
32768