You can use itertools.groupby(it does exactly what you want - groups consecutive elements) and count all groups starting with1
In [1]: from itertools import groupby
In [2]: a = [0,0,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0]
In [3]: len([k for k, _ in groupby(a) if k == 1])
Out[3]: 5
what if I wanted to add a condition that an event is given as long as there are 2 or more between them.
, groupby key:
from itertools import groupby
class GrouperFn:
def __init__(self):
self.prev = None
def __call__(self, n):
assert n is not None, 'n must not be None'
if self.prev is None:
self.prev = n
return n
if self.prev == 1:
self.prev = n
return 1
self.prev = n
return n
def count_events(events):
return len([k for k, _ in groupby(events, GrouperFn()) if k == 1])
def run_tests(tests):
for e, a in tests:
c = count_events(e)
assert c == a, 'failed for {}, expected {}, given {}'.format(e, a, c)
print('All tests passed')
def main():
run_tests([
([0, 1, 1, 1, 0], 1),
([], 0),
([1], 1),
([0], 0),
([0, 0, 0], 0),
([1, 1, 0, 1, 1], 1),
([0, 1, 1, 0, 1, 1, 0], 1),
([1, 0, 1, 1, 0, 1, 1, 0, 0, 1], 2),
([1, 1, 0, 0, 1, 1], 2),
([0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0], 4)
])
if __name__ == "__main__":
main()
- 0 1, . ( 1), ( 0)
, , , [1, 1, 0, 0] [[1, 1, 0], [0]].