Home > Mobile >  Given the X numpy array, return True if any of its elements is zero
Given the X numpy array, return True if any of its elements is zero

Time:05-25

X is given as below:

X = np.array([-1, 2, 0, -4, 5, 6, 0, 0, -9, 10])

My answer is: any(X==0).
But the standard answer is X.any(), and it returns True, which confuses me.

For me, X.any() is looking for if there is any True or 1 in the array. In this case, since there is no 1 in the given X array, it should have returned False. What did I get wrong? Thank you in advance!

CodePudding user response:

X.any() is an incorrect answer, it would fail on X = np.array([0]) for instance (incorrectly returning False).

A correct answer would be: ~X.all(). According to De Morgan's laws, ANY element is 0 is equivalent to NOT (ALL elements are (NOT 0)).

How does it work?

Numpy is doing a implicit conversion to boolean:

X = np.array([-1, 2, 0, -4, 5, 6, 0, 0, -9, 10])
# array([-1, 2, 0, -4, 5, 6, 0, 0, -9, 10])

# convert to boolean
# 0 is False, all other numbers are True
X.astype(bool)
# array([ True,  True, False,  True,  True,  True, False, False,  True, True])

# are all values truthy (not 0 in this case)?
X.astype(bool).all()
# False

# get the boolean NOT
~X.astype(bool).all()
# True
  • Related