UniCoreFW

compress()

Compress a string using a simple run-length encoding.

Implementation

This method compresses the input string by replacing sequences of repeated characters with a single instance of the character followed by a number indicating the count of repetitions. Args: word: The input string to be compressed Returns: A compressed version of the input string

Example

compress("aaabbbccc")

Expected output: '3a3b3c'

Source Code

def compress(word: str) -> str: if not word: return "" comp = [] # Use a list for faster concatenation length = len(word) i = 0 while i < length: count = 1 # Count up to 9 consecutive characters while i + count < length and word[i] == word[i + count] and count < 9: count += 1 # Append the count and character to comp comp.append(f"{count}{word[i]}") # Move to the next distinct character i += count return "".join(comp) # Join the list into a single string at the end