String Compression
Compress string: "aaabb" -> "a3b2".
AdvancedPhase 5 - Category 5: Advanced String LogicExample 12 of 14
string-compression.py
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
What's going on
Count consecutive characters.
Key Concepts:
Track consecutive count
Append char + count when changes
Handle last group
🔗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