“Splitting” the output of a RLE (groupby) depending on a defined value ( the “character” to split the RLE on )
Question
Consider the "string" ( treat it as an array of digits )
0 0 1 8 8 8 1 0
The RLE ( "groupby" ) is:
[(0,2), (1, 1), (8,3), (1, 1), (0, 1)]
We then enrich the above RLE with the sum of the run lengths of the previous elements.
Hence, the enriched version of the above becomes:
[(0, (0,2)), (0+2, (1, 1)), (0+2+1, (8,3)), (0+1+2+3, (1, 1)), (0+1+2+3+1, (0, 1))]
The "string" split on 1:
0 0 , 8 8 8 , 0
RLE split on 1
[(0,2)] , [(8,3)] , [(0, 1)]
The "string" split on 8:
0 0 1 , , , 1 0
RLE split on 8
[(0,2), (1, 1)] , , , [(1, 1), (0, 1)]
Note : In my examples, I have cited the "RLE split on Z" lists without enriching them. This would not be so. I left them out to reduce clutter. For example, the "RLE split on 1" should really be treated as:
[(0, (0,2))] , [(0+2+1, (8,3))] , [(0+1+2+3+1, (0, 1)]
How can I achieve this "RLE split" on Z ( = 1, 8; in this case )
It's fine to leave out empty arrays ( after split ).
Perhaps a clever list comp.? ( it seems a little easier to solve with a for loop with an append nested within )
Solution
Just for show the way how, I strongly advise you not to use this
"elegant" ugly way:
>>> data
[0, 0, 1, 8, 8, 8, 4, 4, 1, 0]
>>> def fromDataToSplitRLE(dat,n):
RLE=[(k,len(tuple(g))) for k,g in itertools.groupby(dat)]
tmp=tuple(zip(*RLE))
return [list(g) for k,g in itertools.groupby((zip((sum(tmp[1][:i]) for i in range(len(tmp[1]))) ,(zip(*tmp)))),lambda x:x[1][0]!=n) if k]
>>> fromDataToSplitRLE(data,1)
[[(0, (0, 2))], [(3, (8, 3)), (6, (4, 2))], [(9, (0, 1))]]
OTHER TIPS
import itertools
def get_rle(list_of_digits, split_on=None):
count = 0
rle = []
active_group = []
rle_app = rle.append
for item, group in itertools.groupby(list_of_digits):
L = len(list(group))
if item == split_on:
rle_app(active_group)
active_group = []
else:
active_group.append((count, (item, L)))
count += L
rle_app(active_group)
return rle
list_of_digits = map(int, '0 0 1 8 8 8 1 0'.split())
print get_rle(list_of_digits)
print get_rle(list_of_digits, 8)
print get_rle(list_of_digits, 1)
aaron@aaron-laptop:~/code/tmp$ python rle.py
[[(0, (0, 2)), (2, (1, 1)), (3, (8, 3)), (6, (1, 1)), (7, (0, 1))]]
[[(0, (0, 2)), (2, (1, 1))], [(6, (1, 1)), (7, (0, 1))]]
[[(0, (0, 2))], [(3, (8, 3))], [(7, (0, 1))]]