views:

235

answers:

4

I am trying to understand lambdas and I get the idea but how do I define multiple conditions for a Point2 [x,y] comparison, so something like:

if x1 < x2: -1
if x1 == x2: 0
if x1 > x2: 1
+2  A: 

EDIT: Updated to be real Python according to PEP308 :) Note that the PEP has interesting information about how this should be parenthesized depending on which version of Python you're using. I won't attempt to reproduce it here - just read the PEP!

How about:

-1 if x1 < x2 else (0 if x1 == x2 else 1)

(That's without any knowledge of Python lambda expressions, but it's a fairly common way of expressing this logic in a single expression, which I guess is what you're after.)

EDIT: Others have suggested using cmp - I've been assuming that the questioner actually wants more complicated logic, such as providing their own comparisons, but wants the general form of "choose from a few conditions in a single expression".

Jon Skeet
Thanks Jon. I was surprised to see you reply to a python question but knew you would have great lambda knowledge from C# :)
Joan Venge
thats not valid python
Johannes Weiß
Doh - looked at a Python page, but it was giving an example from PHP. Aargh. Trying to do too many things at once.
Jon Skeet
Updated to real Python.
Jon Skeet
+4  A: 

The code above is equivalent to:

cmp(x1,x2)

or in a (ugly) lambda expression:

lambda x1,x2: 1 if x1>x2 else (0 if x1==x2 else -1)

(works only in Python 2.6 and above).

Normally you should use lambda expressions only for functions like

def fun(...):
    return ...
Johannes Weiß
When you say:if x1>x2what does it return? It just goes to else?
Joan Venge
1 if x1>x2 else (0 if x1==x2 else -1) is the python equivalent of Javas: x1>x2?1:(x1==x2?0:-1). And yes it tries x1>x2 if that is False, it takes the value after else, if True it takes the value before the it (1 in that case)
Johannes Weiß
From PEP 308, it looks like it will work in Python 2.5 if you put brackets in: "lambda x1,x2: (1 if x1>x2 else (0 if x1==x2 else -1))" - but I can't easily test that.
Jon Skeet
Thanks Jon, didn't know that.
Joan Venge
Neither did I before reading the PEP :)
Jon Skeet
+4  A: 
my_compare = lambda x1,x2 : cmp(x1, x2)
my_compare( -100, 100 )
codelogic
Good one codelogic.
Joan Venge
my_compare = cmp; my_compare(-100, 100)
Ken
Better yet, just: cmp(-100, 100) Code was purely to demonstrate lamda usage.
codelogic
+3  A: 

In such a case, lambda expressions aren't usually the best thing. As Jon Skeet mentioned, you're gonna end with multiple if-else expressions:

lambda x1, x2: -1 if x1 < x2 else (0 if x1 == x2 else -1)

For your specific problem:

lambda x1, x2: cmp(x1, x2)

is the way to go.

Mike Hordecki