1

I need to assert that all numeric values in an array are either negative or non-negative.

I wrote this:

def check(arr):
    return all([i < 0 for i in arr]) or all([i >= 0 for i in arr])

And this, which is slightly more efficient I suppose:

def check(arr):
    temp = [i < 0 for i in arr]
    return all(temp) or not any(temp)

I would like to know if there's a cleaner / more pythonic way, or perhaps some arithmetic trick which I can use instead.

halfer
  • 19,471
  • 17
  • 87
  • 173
goodvibration
  • 5,556
  • 4
  • 21
  • 50

1 Answers1

2

One way is to use a set comprehension to derive a set of Boolean values. This set will be either {True}, {False} or {True, False}. Then test if your set has length equal to 1.

def check(arr):
    return len({i < 0 for i in arr}) == 1
jpp
  • 147,904
  • 31
  • 244
  • 302