String Compression
Encode adjacent character runs as character-count pairs. Students reset a run counter, flush completed runs, and include the final run after traversal.
1# Take string2s = input("Enter string: ")34# Compress5if not s:6 compressed = ""7else:8 compressed = ""9 count = 110 for i in range(1, len(s)):11 if s[i] == s[i-1]:12 count += 113 else:14 compressed += s[i-1] + str(count)15 count = 116 compressed += s[-1] + str(count)1718print(f"Compressed: {compressed}")
Output
Enter string: aaabbcc Compressed: a3b2c2
In this one
- Count adjacent runs
- Reset on character changes
- Flush the final run
How it works
- 1
Start a nonempty run count at one.
- 2
Append a completed character-count pair on each change.
- 3
Append the last run after traversal.
Edge cases
Why append after the loop?
Why append after the loop?
The final run has no later different character to trigger a flush.
Does compression always reduce length?
Does compression always reduce length?
No. Short runs can make the encoded string longer.
What's going on
Equal neighboring characters increase count. A change appends the previous character and its count, then begins a new run at one.
After the loop, the last run is appended explicitly. aaabb becomes a3b2. This run-length encoding is not guaranteed to shorten text: abc becomes a1b1c1. Empty input is handled separately, avoiding access to s[-1] when no character exists.
Why append after the loop? The final run has no later different character to trigger a flush.
Does compression always reduce length? No. Short runs can make the encoded string longer.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does aaa become?
Pick an answer to check it.
Question 2
Why append after the loop?
Pick an answer to check it.
Questions people ask
Why append after the loop?
The final run has no later different character to trigger a flush.
Does compression always reduce length?
No. Short runs can make the encoded string longer.
What does aaa become?
a3.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum