VOOZH about

URL: https://www.geeksforgeeks.org/python/run-length-encoding-python/

⇱ Run Length Encoding in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Run Length Encoding in Python

Last Updated : 26 Nov, 2024

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:


Output
w3x3w3

Using Regular Expressions

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

Another code:


Output
w3x3w3
Comment
Article Tags: