0

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)
8
  • 1
    If you are new to programming you might want to do something a little simpler with lambdas first and understand how they work, as it stands your code is not remotely near working. Commented Oct 6, 2015 at 19:18
  • "I've read a guide and watched a lecture on using lambda as an argument". Got links? Commented Oct 6, 2015 at 19:19
  • Yes The guide is pythonconquerstheuniverse.wordpress.com/2011/08/29/… and the last ~5 minutes here ocw.mit.edu/courses/electrical-engineering-and-computer-science/… Commented Oct 6, 2015 at 19:20
  • z is a function, so you probably don't want to print it, but rather its return value when called: print(z()). However, z in the body of the function will also refer to the argument passed to Coord (that is, to itself), so it's not clear where the actual value you want is coming from. Commented Oct 6, 2015 at 19:21
  • There's also an extra ) or something. Commented Oct 6, 2015 at 19:22

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

It might be worth noting that, in this context, a function with a descriptive name probably makes more sense.
Thanks, your answer clarified a lot for me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.