50 XP

24. Run-length encoding

Intermediate strings loops

Run-length encoding is a simple way to shorten text with many repeats. A run is a group of the same character side by side: aaabcc has three runs, aaa, b and cc.

Write a function rle(text) that takes a string and returns its encoding: for each run, in order, the character followed by how many times it repeats.

  • Write the count even when it is 1: a single b becomes b1.
  • A count can have more than one digit, such as 12.
  • When a character comes back later, it starts a new run, written on its own.
  • If text is empty, return an empty string "".

Example 1

Inputtext = "aaabcc"
Output"a3b1c2"
ExplanationThree a's, one b, two c's.

Example 2

Inputtext = "abc"
Output"a1b1c1"
ExplanationEvery run is one character long.

Example 3

Inputtext = "aabaa"
Output"a2b1a2"
ExplanationThe a's come in two runs, written apart.

Constraints

  • text has 0 to 100 characters, all lower-case letters.

Submit also runs 4 more tests you can't see.

Practises For Loops (lesson 13).

Code
def rle(text):
    """Run-length encode a string, like "aaab" -> "a3b1".

    text: str; may be empty
    Returns: str, each run's character followed by how
        many times it repeats
    """
    # Write your code here
    pass