import itertools

def run_length_encode2(lst):

# could just reuse run_length_encode function from last time

groups = [list(x[1]) for x in itertools.groupby(lst)]

return [len(g) > 1 and (len(g), g[0]) or g[0] for g in groups]

Hmmm.... I use 2.4 at work, but I need to keep up with the times, so here is the more modern way (let's get ternary with it)

import itertools

def _run_length_encode2(lst):

groups = [list(x[1]) for x in itertools.groupby(lst)]

return [(len(g), g[0]) if len(g) > 1 else g[0] for g in groups]

## No comments:

Post a Comment