
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to encode a string in normal form to its run-length form in Python
Suppose we have a string s. We have to encode this by using run-length encoding technique. As we know, run-length encoding is a fast and simple method of encoding strings. The idea is as follows − The repeated successive elements (characters) as a single count and character.
So, if the input is like s = "BBBBAAADDCBB", then the output will be "4B3A2D1C2B"
To solve this, we will follow these steps −
- res := blank string
- tmp := first character of s
- count := 1
- for i in range 1 to size of s, do
- if s[i] is not same as tmp, then
- res := res concatenate count concatenate tmp
- tmp := s[i]
- count := 1
- otherwise,
- count := count + 1
- if s[i] is not same as tmp, then
- return res concatenate count concatenate tmp
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s): res = "" tmp = s[0] count = 1 for i in range(1,len(s)): if s[i] != tmp: res += str(count) + tmp tmp = s[i] count = 1 else: count += 1 return res + str(count) + tmp ob = Solution() print(ob.solve("BBBBAAADDCBB"))
Input
"BBBBAAADDCBB"
Output
4B3A2D1C2B
- Related Articles
- Program to decode a run-length form of string into normal form in Python
- Program to implement run length string decoding iterator class in Python
- Program to find longest consecutive run of 1s in binary form of n in Python
- How to convert CFG to Greibach Normal Form?
- Program to find minimum length of lossy Run-Length Encoding in Python
- Program to find number of ways to form a target string given a dictionary in Python
- Explain Chomsky normal form in TOC
- First Normal Form (1NF)
- Second Normal Form (2NF)
- Fifth Normal Form (5NF)
- Third Normal Form (3NF)
- Domain-Key Normal Form
- Fourth Normal Form (4NF)
- Sixth Normal Form (6NF)
- Create an example table that is in its first normal form(DBMS)

Advertisements