Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a string with counts of streaks

Let's say I have a string of the following form:

"000000111100011100001011000000001111"

and I want to create a list containing the lengths of the 1-streaks:

[4, 3, 1, 2, 4]

Is there a nice one-liner for this?

like image 821
user2597879 Avatar asked Dec 12 '22 13:12

user2597879


2 Answers

If you don't mind the from itertools import groupby...

>>> from itertools import groupby
>>> [len(list(g)) for k, g in groupby(s) if k == '1']
[4, 3, 1, 2, 4]
like image 120
Jon Clements Avatar answered Dec 29 '22 07:12

Jon Clements


Can be done with regex, though not quite as elegant as the itertools solutions

answer = [len(item) for item in filter(None, re.split(r"[^1]+", test_string))]

Or, more elegant:

answer = [len(item) for item in re.findall(r"1+", test_string)]

and more elegant still (credits to Jon):

answer = map(len, re.findall("1+", test_string))
like image 26
Slater Victoroff Avatar answered Dec 29 '22 08:12

Slater Victoroff