goodvibration
goodvibration

Reputation: 6206

Check if two values are both non-negative or both negative

Given a pair of integer values, I need to check if both are non-negative or both are negative.

The trivial way is:

def func(a, b):
    return (a >= 0 and b >= 0) or (a < 0 and b < 0)

But I am looking for something "neater", which I believe to be possible, so I came up with this:

def func(a, b):
    return (a >= 0) ^ (b >= 0) == 0

However, this one feels a little "obscure to the average reader".

Is there a cleaner way?

Upvotes: 1

Views: 1333

Answers (2)

cs95
cs95

Reputation: 402493

Multiply them and test against 0:

def func(a, b):
    return a * b >= 0

Upvotes: 13

Adam Barnes
Adam Barnes

Reputation: 3203

This is Python. We're not about the most concise efficient possible way to do things in all cases - that's for the C++ lads to do.

If (a >= 0 and b >= 0) or (a < 0 and b < 0) is "fast enough", (which would surprise me if not the case), then stick with it. It works, and is VERY obvious what it does.

For either your second solution, or @coldspeed's, I personally would have to write some stuff down on paper to figure out what it's doing, unless the function name was a LOT better than func.

Upvotes: 3

Related Questions