How do I find the length of a run of numbers in a list? (Is there a faster way than what I'm doing?)

list, python

Solution

I might use `itertools.groupby` for this one

lst = [ 1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0]

from itertools import groupby
from operator import itemgetter

for k,v in groupby(enumerate(lst),key=itemgetter(1)):
    if k:
        v = list(v)
        print v[0][0],v[-1][0]

This will print the start and end indices of the groups of 1's

Problem

I have a list that contains either 1's or 0's; nothing else. I am interested in finding the 1's and, more specifically, where a run of 1's starts and where that run ends (or in the code below, the "length" of that run of 1's....it can either be the "length" of that run or the ending index position of that run, as I can do math and figure out the length from the start and ending positions). I'm storing the runs of 1's in a hash. Is there a faster way to get what I'm after than what I have? I'm still learning python and the list I am using in real life is much, much larger, so speed is important. ``` previous = 0 cnt = 0 startLength = {} for r in listy: if previous == 0 and r == 1: start = cnt startLength[start] = 1 if previous == 1 and r == 1: startLength[start] = 1 + cnt - start previous = r cnt += 1 for s,l in startLength.iteritems(): print "A run of 1's starts at position %s and lasts %s" % (s,l) ```

Original source

Related problems