2

I have a list of 0s and 1s and I want to know how often 0 occures successively. I wrote a quick and dirty solution. However, I believe it is slow

For example

a = [0,0,0,1,1,1,0,0,0,1,1,0,0]
def duration(a):   
    b = "".join([str(x) for x in a])
    return [len(x) for x in b.split("1") if len(x)>0]
print(duration(a))

gives the correct output ([3,3,2]). I am convinced that there is a much faster way of doing it.

Thanks,

glostas

Glostas
  • 1,090
  • 2
  • 11
  • 21

2 Answers2

3

itertools.groupby

from itertools import groupby

[len([*g]) for k, g in groupby(a) if k == 0]

[3, 3, 2]

As pointed out in Óscar López's answer, using the syntax list(g) is compatible with older versions of python.

[len(list(g)) for k, g in groupby(a) if k == 0]

for

result = []
count = 0
something_not_zero = 1
for e in [*a, something_not_zero]:
    if e == 0:
        count += 1
    elif count > 0:
        result.append(count)
        count = 0

result

[3, 3, 2]
piRSquared
  • 285,575
  • 57
  • 475
  • 624
2

A slight variation on @piRSquared's answer (also using itertools.groupby). This should work in older versions of Python, too:

from itertools import groupby

def duration(a):
    return [len(list(g)) for k, g in groupby(a) if k == 0]

For example:

duration([0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0])
=> [3, 3, 2]
Óscar López
  • 232,561
  • 37
  • 312
  • 386