myo-kun
myo-kun

Reputation: 5

How to return True if two-dimensional array in python has at least one True

I'm trying to write a code which checks if 2D-array (consists of only boolean) has at least one True and return True if there is at least one True.

I tried using all() function but couldn't come up with a solution. I assume what I need is opposite of what all() function does.

>>> array1 = [[True, False], [False, False]]
>>> all([all(row) for row in array1)
False # This should be True
>>> array2 = [[False, False], [False, False]]
>>> all([all(row) for row in array2)
False # This is correct but this and array with all True is only working case.

For array1 = [[True, False], [False, False]], I expect the output to be True since there is one True at array1[0][0].

Upvotes: 0

Views: 1538

Answers (3)

user2717954
user2717954

Reputation: 1902

def has_true(arr):
    return any(any(row) for row in arr)

In [7]: array1 = [[True, False], [False, False]]

In [8]: array2 = [[False, False], [False, False]]

In [9]: has_true(array1)
Out[9]: True

In [10]: has_true(array2)
Out[10]: False

this answer is using generators so it will return upon finding the first True value without running over the whole matrix. in addition it will use O(1) space

edit: removed unnecessary code

Upvotes: 2

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

A much shorter approach is to chain the lists together using itertools.chain and apply any on them

from itertools import chain

def has_true(arr):
    return any(chain(*arr))

print(has_true([[True, False], [False, False]]))
print(has_true([[False, False], [False, False]]))

The output will be

True
False

Upvotes: 0

Raja
Raja

Reputation: 26

use any() instead of all(). all() return true if all items in an iterable object are true. any() Returns True if any item in an iterable object is true.

Upvotes: 0

Related Questions