0

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].

3 Answers 3

2
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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This what I came up after seeing your code; any([any(row) for row in array]). It would be great if you could tell me this is an alternative way.
I will edit my post, your approach is correct but it should use generators
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.