Use itertools.groupby()
to group elements, then count each group. Using the any()
function lets you exit the loop early if a match was found:
from itertools import groupby, islice
print any(sum(1 for _ in islice(g, 3)) == 3 for k, g in groupby(myList) if k)
The if k
filters the groups to only count the groups of True
values.
The itertools.islice()
function ensures we only look at the first 3 elements of a group, and ignore the rest of that group. This way you avoid having to count the next however many True
values just to determine that you found at least 3.
Demo:
>>> from itertools import groupby, islice
>>> myList = [True, True, False, False, True, False, True, False, False]
>>> [sum(1 for _ in islice(g, 3)) for k, g in groupby(myList) if k]
[2, 1, 1]
>>> any(sum(1 for _ in islice(g, 3)) == 3 for k, g in groupby(myList) if k)
False
>>> myList = [True, True, False, False, True, True, True, True, False, True, False, False]
>>> [sum(1 for _ in islice(g, 3)) for k, g in groupby(myList) if k]
[2, 3, 1]
>>> any(sum(1 for _ in islice(g, 3)) == 3 for k, g in groupby(myList) if k)
True
I used a list comprehension to show the group sizes (counting only True
groups) to show why the any()
call returns False
first, then True
; the second example has a group of 4 consecutive True
values.