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.
Related
can anyone can help me I was expected that the output is 625 but it shows the output is zero
def add(*args):
sum = 0
for i in args:
sum *= i
return sum
print(add(5, 5, 5, 5))
As the value of sum = 0
And, you multiplying the values with 0. Therefore, you are getting no answer.
Change this line
sum = 0
To:-
sum = 1
Thank You.
You are setting the sum variable to 0, an in the for loop you are multiplying the sum with i. Any number multiplied with 0 is 0.
>>> def multiply(*args):
... result = 1
... for i in args:
... result *= i
... return result
...
>>> print(multiply(5,5,5,5))
625
Or rather if you wanted to add
>>> def add(*args):
... result = 0
... for i in args:
... result += i
... return result
...
>>> print(add(5,5,5,5))
20
Or rather do this pythonic way
>>> mul = lambda x,y: x*y
>>> functools.reduce(mul, [5,5,5,5])
625
Or rather single liner
>>> functools.reduce(lambda x,y : x*y, [5,5,5,5])
625
>>> functools.reduce(lambda x,y : x+y, [5,5,5,5])
20
Please define your function to have meaningful names.
Don't use inbuilt names like "sum"
Have meaningful variable names
First of all, anything multiplied by zero is zero. Therefore if you want to multiply the numbers received, you need to change sum = 0 to sum = 1.
Secondly, don't use sum as a variable or function name, as it is a built-in function in python. It is also misleading as you want your function to multiply the given args (and therefore also don't call the function add). To achieve a readable code, you should have meaningful variable and function names.
Also, your first line isn't indented correctly. You can read about python indentation here.
Putting it all together:
def multiply(*args):
multiplication = 1
for i in args:
multiplication *= i
return multiplication
print(multiply(5, 5, 5, 5))
Output:
625
I am researching the lambda function, and I came across this code sample:
def myfunc(n):
return lambda a : a * n
tripler = myfunc(3)
print(tripler(10)) # Output: 30
I understand that when tripler is assigned to the return value from the myfunc function, the value of 3 is passed as an argument and from within the function, it is represented as 'n'. But lambda uses a bound variable labeled 'a'. So at this point, ignoring the final print line, I'm not sure how 'a' is factored into this. When I run this code, I receive no errors.
I would be interested in understanding how this code is processed and how it comes up with its conclusion without generating errors.
The return value of myfunc is a closure, which retains a reference to the argument passed to myfunc.
>>> x = myfunc(3)
>>> x.__closure__[0].cell_contents
3
When you call x, the value is used.
>>> x(10) # (lambda a: a * n)(10), with n == 3
30
You can see this in the byte code generated for x:
>>> import dis
>>> dis.dis(x)
2 0 LOAD_FAST 0 (a)
2 LOAD_DEREF 0 (n)
4 BINARY_MULTIPLY
6 RETURN_VALUE
LOAD_FAST references the local variables (in this case, the only local variable is the parameter a), while LOAD_DEREF references the closure. The argument 0 is an index into the tuple stored in x.__closure__.
I don't really get how that works, why is 10 not an variable of the function? I never saw a case where you would apply a function to an item outside of that function. I don't want the answer to the problem, just want to understand it.
Thanks guys
Write a function called general_poly, that meets the specifications below.
For example, general_poly([1, 2, 3, 4])(10) should evaluate to 1234 because 1∗103+2∗102+3∗101+4∗100
So in the example the function only takes one argument with general_poly([1, 2, 3, 4]) and it returns a function that you can apply to a value, in this case x = 10 with general_poly([1, 2, 3, 4])(10).
It's asking you for general_poly to return a function, e.g.:
def general_poly(L):
def inner(x):
return sum(x+e for e in L)
return inner
general_poly([1,2,3,4])(10)
# 11+12+13+14 = 50
This should give you enough to be able to work through your homework.
def general_poly (L):
""" L, a list of numbers (n0, n1, n2, ... nk)
Returns a function, which when applied to a value x, returns the value
n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """
def inner(x):
L.reverse()
return sum(e*x**L.index(e) for e in L)
return inner
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.
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.