Ahoomaha
Ahoomaha

Reputation: 13

Python lambda used as an argument, calling other arguments from parent function

I'm new to programming and am having a little trouble understanding the lambda function in Python. I understand why it's used and its effectiveness. Just having trouble learning to apply it. I've read a guide and watched a lecture on using lambda as an argument. I've tried using the map function. Not sure if that's the correct approach, but this is my broken code in its most basic form:

def Coord(x, y, z=lambda: z*2 if z < x or z < y else z)):
    print(z)
Coord(10,20,30) 
Coord(10,20,12) 
Coord(10,20,8) 

Needs to return 30, 24, and 32, respectively. Working code without using lambda:

def Coord(x, y, z):
    while z < x or z < y:
        z*=2
print(z)

Upvotes: 0

Views: 1843

Answers (1)

mescarra
mescarra

Reputation: 725

You cannot use other parameters from the Coord function in your default parameter definition for z (which is a lambda function in your case).

You may want to do something like this:

def Coord(x, y, w, z=lambda a,b,c: c*2 if c < a or c < b else c):
    print(z(x,y,w))

or

def Coord(x, y, w):
    z=lambda: w*2 if w < x or w < y else w
    print(z())

Both definitions are equivalent when evaluating them with 3 arguments, and they result in:

>>> Coord(10,20,30)
30
>>> Coord(10,20,12)
24
>>> Coord(10,20,8)
16

Upvotes: 1

Related Questions