Open In App

Run Length Encoding in Python

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an input string, write a function that returns the Run Length Encoded string for the input string. For example, if the input string is ‘wwwwaaadexxxxxx’, then the function should return ‘w4a3d1e1x6’. 

Examples:

Input  :  str = 'wwwxxxwww'
Output : 'w3x3w3'

This problem has existing solution please refer Run Length Encoding link. In the simplest approach, we iterate through the string, track the current character and count its consecutive occurrences. When a different character is encountered, we append the current character and its count to the result.

Steps:

  • Initialize a count variable to 1.
  • Traverse the string and count consecutive characters.
  • When the character changes, append the character and its count to the result.
  • If the string ends, append the last character and its count.

Implementation:

Python
# Function to perform Run-Length Encoding using a simple iterative approach
def runLengthEncodingIterative(input):
    output = ''
    
    # We start with the first character
    count = 1  
    
    # Loop through the string starting from the second character
    for i in range(1, len(input)):
      
       # If the current character is the same as the previous one
        if input[i] == input[i - 1]: 
            count += 1  # Increment the count
        else:
          
          	# Add previous character and its count to output
            output += f"{input[i - 1]}{count}"  
            
            # Reset count for the new character
            count = 1  
    
    # After the loop, we still need to add the last character group
    output += f"{input[-1]}{count}"
    
    return output

# Driver code
input = "wwwxxxwww"
print(runLengthEncodingIterative(input))  # Expected output: w3x3w3

Output
w3x3w3

Using Regular Expressions

This approach uses regex to find consecutive characters and count their occurrences.

Another code: 

Python
from itertools import groupby  

# Function to perform Run-Length Encoding using itertools.groupby
def runLengthEncodingGroupby(input):
  
    # Initialize an empty string to store the final result
    output = ''
    
    # Group the string by consecutive characters and count the occurrences
    for char, group in groupby(input):
      	# Counting the occurrences of the character	
        count = len(list(group)) 
        
        # Appending the character and its count to the output string
        output += f"{char}{count}"  
    
    return output

# Driver code
input = "wwwxxxwww"
print(runLengthEncodingGroupby(input))  # Expected output: w3x3w3

Output
w3x3w3

 



Next Article
Practice Tags :

Similar Reads