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,824
  • 17
  • 99
  • 186
goodvibration
  • 5,980
  • 4
  • 28
  • 61

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
  • 159,742
  • 34
  • 281
  • 339