24. Run-length encoding
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
bbecomesb1. - 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
textis empty, return an empty string"".
Example 1
text = "aaabcc""a3b1c2"Example 2
text = "abc""a1b1c1"Example 3
text = "aabaa""a2b1a2"Constraints
texthas 0 to 100 characters, all lower-case letters.
Submit also runs 4 more tests you can't see.
Practises For Loops (lesson 13).
- Go through the text remembering two things: the character of the current run, and how many times you have seen it in a row.
- When the next character is the same, add 1 to the count. When it differs, the run is over: add the character and
str(count)to the result, and start a new run with a count of 1. - The last run ends with the text, not with a different character, so add it after the loop. An empty text has no runs: return
""before you look attext[0].
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.