3

this is probably really easy to do but I am looking to calculate the length of consecutive positive occurrences in a list in python. For example, I have a and I am looking to return b:

a=[0,0,1,1,1,1,0,0,1,0,1,1,1,0]

b=[0,0,4,4,4,4,0,0,1,0,3,3,3,0]

I note a similar question on Counting consecutive positive value in Python array but this only returns consecutive counts but not the length of the belonging group.

Thanks

Community
  • 1
  • 1
Peter
  • 77
  • 1
  • 6
  • would prefer to use a simple loop if possible but open to suggestions. computational speed is also important. – Peter May 26 '15 at 05:05

3 Answers3

5

This is similar to a run length encoding problem, so I've borrowed some ideas from that Rosetta code page:

import itertools
a=[0,0,1,1,1,1,0,0,1,0,1,1,1,0]

b = []
for item, group in itertools.groupby(a):
    size = len(list(group))
    for i in range(size):
        if item == 0:
            b.append(0)
        else:
            b.append(size)

b
Out[8]: [0, 0, 4, 4, 4, 4, 0, 0, 1, 0, 3, 3, 3, 0]
Marius
  • 58,213
  • 16
  • 107
  • 105
1

At last after so many tries came up with these two lines.

In [9]: from itertools import groupby

In [10]: lst=[list(g) for k,g in groupby(a)]

In [21]: [x*len(_lst) if x>=0 else x for _lst in lst for x in _lst]
Out[21]: [0, 0, 4, 4, 4, 4, 0, 0, 1, 0, 3, 3, 3, 0]
Ajay
  • 5,267
  • 2
  • 23
  • 30
0

Here's one approach.

The basic premise is that when in a consecutive run of positive values, it will remember all the indices of these positive values. As soon as it hits a zero, it will backtrack and replace all the positive values with the length of their run.

a=[0,0,1,1,1,1,0,0,1,0,1,1,1,0]

glob = []
last = None
for idx, i in enumerate(a):
    if i>0:
        glob.append(idx)
    if i==0 and last != i:
        for j in glob:
            a[j] = len(glob)
        glob = []

# > [0, 0, 4, 4, 4, 4, 0, 0, 1, 0, 3, 3, 3, 0]
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159