1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
goodvibration
  • 5,980
  • 4
  • 28
  • 61

2 Answers2

13

Multiply them and test against 0:

def func(a, b):
    return a * b >= 0
cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thank you. Is this agnostic to integer size? I am dealing with extremely large values. – goodvibration Mar 06 '18 at 11:58
  • 1
    @goodvibration yes, python ints have no limit besides your system memory. – cs95 Mar 06 '18 at 11:58
  • @goodvibration Python integers are always arbitrary precision, so no overflow. – Zinki Mar 06 '18 at 11:59
  • @monamona Hmm, here's [another question](https://stackoverflow.com/q/45164645/4909087) for which I though the answer to be obvious, but apparently not, judging by the votes on the accepted answer :) – cs95 Mar 06 '18 at 12:00
  • @cᴏʟᴅsᴘᴇᴇᴅ I correct myself. You are an absolute genious! Maybe you are not concerned by "déformation professionelle"... – monamona Mar 06 '18 at 14:39
3

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.

Adam Barnes
  • 2,922
  • 21
  • 27