Python problem 18 of 30

Run-length encoding

  • Python
  • Medium

Write rle(s) that compresses runs of repeated characters into the character followed by the run length.

rle("aaabcc")   # "a3b1c2"
rle("")         # ""
Show hint

itertools.groupby groups consecutive equal items for you.

Show solution
from itertools import groupby

def rle(s):
    return "".join(
        f"{ch}{len(list(run))}"
        for ch, run in groupby(s)
    )

groupby yields each character with an iterator over its run, so counting the run gives the length. O(n) time. Doing it with a manual loop and a counter is a good exercise too. Watch the last run, which is where most hand-written versions slip.

Want a problem like this every day? See today's problem and keep a streak going.