user2597879
user2597879

Reputation: 97

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?

Upvotes: 4

Views: 365

Answers (5)

dansalmo
dansalmo

Reputation: 11696

No regex needed, just str.split

>>> mystr = "000000111100011100001011000000001111"
>>> [len(s) for s in mystr.split('0') if s]
[4, 3, 1, 2, 4]

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 114025

>>> mystr = "000000111100011100001011000000001111"
>>> [len(s) for s in re.split("0+", mystr) if s]
[4, 3, 1, 2, 4]

Upvotes: 1

Slater Victoroff
Slater Victoroff

Reputation: 21914

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))

Upvotes: 2

Jon Clements
Jon Clements

Reputation: 142206

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]

Upvotes: 15

RussW
RussW

Reputation: 437

>>> s = "000000111100011100001011000000001111"
>>> items = set(s)
>>> counts = [s.count(x) for x in items]
>>> counts
[1, 1]
>>> 

Upvotes: -6

Related Questions