Skip to content Skip to sidebar Skip to footer

Finding A Consecutive 'True' Boolean Values In A List

list=[False, True,True,False,False,True, True] In that list, I want to find the starting position of True and how many they are such that the list should return: [[1,2], [6,2]] I

Solution 1:

What do you consider special? This turns the list of Booleans into a string of Xs and Os and then uses re.finditer to find the spans of Xs or Trues:

import re
import operator

x = [False, True,True,False,False,True, True]
s = ''.join('X' if p else 'O' for p in x)
list([m.span()[0], abs(operator.sub(*m.span()))] for m in re.finditer('X+', s))

And here is another that uses enumerate and itertools.groupby:

import itertools

list((g[0][0], len(g)) 
    for key, group in itertools.groupby(enumerate(x), key=lambda v: v[1]) 
    if key 
    for g in (list(group),))

Solution 2:

from itertools import groupby

l = [False, True,True,False,False,True, True]

results = []
for k, g in groupby(enumerate(l), key=lambda x: x[1]):
    if k: # k is True
        g = list(g) # for example: [(1, True), (2, True)]
        results.append([g[0][0], len(g)]) # for example: [1, 2]
print(results)

Prints:

[[1, 2], [5, 2]]

Solution 3:

lists=[False, True,True,False,False,True, True]
counter=0
consecutive_index=[]
pos = -1

for idx, val in enumerate(lists):
    if val==True and pos == -1:
        counter += 1
        pos = idx
    elif val == True:
        counter += 1
    elif pos != -1:
        consecutive_index.append([pos,counter])
        pos = -1
        counter = 0
if counter > 0:
    consecutive_index.append([pos,counter])

Brute forcing as mentioned in the question. I am keeping a track of index where the "True" begins and maintaining a counter of it, as soon as i read a false i reset the counter and the tracking index to -1 and also append the [tracking index, counter] to the answer list.


Post a Comment for "Finding A Consecutive 'True' Boolean Values In A List"