-2

I have a string which contains only 0 and 1. I need to encode it in a form of ranges of 1's.

Example input:

01101110

Example output:

[[1,2], [4,6]]

Update: Need to produce [begin,end] array of 1's sequence indexes.
As per example: First sequence of 1's starts at index 1 and finishes at index 2. Second sequence starts at index 4 and finishes at index 6
Minimum length of sequence is 1. So "1" input produces [[0,0]] output

How should I do it?

WhiteNinja
  • 93
  • 1
  • 9

1 Answers1

1

Here is one way with groupby:

from itertools import groupby

string = '01101110'

start = 0
out = []
for k,g in groupby(string):
    delta = len(list(g))    
    if k == '1':
        out.append([start,start+delta-1])
    start += delta

print(out)

Returns:

[[1, 2], [4, 6]]
Anton vBR
  • 18,287
  • 5
  • 40
  • 46