Python - Contiguous Boolean Range


Given a list of values, we are interested to know at which position are the Boolean values present as a contiguous list. Which means after we encounter a value which is TRUE there is a continuous value of true from that position until FALSE value is found. Similarly when a FALSE is found there is a contiguous value of FALSE until TRUE is found.

With itertools

W can use accumulate along with groupby from the itertools module. In this example we take a given list and then apply the accumulate function to keep track of the values that are brought together using the sum function.The last value in the list is the last position where the given list ends.

Example

from itertools import accumulate, groupby

# Given list
listA = [False, True,True,False,False]

print("Given list : \n",listA)

# Applying accumulate
res = [0] + list(accumulate(sum(1 for x in y)
for x, y in groupby(listA)))

# Result
print("Positions for Range of contigous values:\n ",res)

Output

Running the above code gives us the following result −

Given list :
[False, True, True, False, False]
Positions for Range of contigous values:
[0, 1, 3, 5]

Using enumerate

The enumerate function along with zip function is used to list the position by comparing each element with the next one. If they are not equal then a new position value is consideredas the staring point of the contiguous range.

Example

 Live Demo

# Given list
listA = [False, True,True,False,False]

print("Given list : \n",listA)

# Applying enumerate
res = [e for e, (x, y) in
enumerate(zip([2]+ listA, listA + [2])) if x != y]

# Result
print("Positions for Range of contigous values:\n ",res)

Output

Running the above code gives us the following result −

Given list :
[False, True, True, False, False]
Positions for Range of contigous values:
[0, 1, 3, 5]

Updated on: 10-Jul-2020

254 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements