Sunday, October 26, 2008

99 problems - python - 11

Modified run-length encoding. Modify the result of problem 10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N E) lists.

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: