216. Python Program to Compress a String with Letter Counts
MediumPhase 2 · Practice
This one takes a few steps: a loop over positions, str() and + on strings. You know all three.
Overview
String compression is a common interview question. Some simple image files use the same idea to save space.
Problem Statement
Lin sends long codes by text message. To make them shorter, Lin writes each group of the same letter as the letter and how many times it comes in a row.
- A run is a group of the same letter next to each other. In
aaabccdd, the runs areaaa,b,ccanddd. - Write each run as the letter and then its count:
aaabecomesa3. - A run of one letter gets its count too:
bbecomesb1. - A letter that comes back later starts a new run.
- Capital and small letters are different letters.
- Print
Compressed: <text>.
Examples
Example 1. Input aaabccdd gives:
Compressed: a3b1c2d2
Why: the runs are 3 times a, 1 time b, 2 times c and 2 times d.
Example 2. Input aabaa gives:
Compressed: a2b1a2
Why: the two groups of a are not next to each other, so each group is its own run.
Input
One word of letters only (1 letter or more). Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line: Compressed:, a space, and the compressed text. The tests try 7 different inputs, also one letter, no repeats and a run of more than 9 letters.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.