

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to perform string compression in Python
Suppose we have a string s. We have to compress this string into Run length encoding form. So when a character is repeated k number of times consecutively like 'bbbb' here letter 'b' is repeated four times consecutively, so the encoded form will be 'b4'. For single characters we shall not add the count into it.
So, if the input is like s = "abbbaaaaaaccdaaab", then the output will be ab3a6c2da3b
To solve this, we will follow these steps −
- res := blank string
- cnt := 1
- for i in range 1 to size of s - 1, do
- if s[i - 1] is same as s[i], then
- cnt := cnt + 1
- otherwise,
- res := res concatenate s[i - 1]
- if cnt > 1, then
- res := res concatenate cnt
- cnt := 1
- if s[i - 1] is same as s[i], then
- res := res + last character of s
- if cnt > 1, then
- res := res concatenate cnt
- return res
Example
Let us see the following implementation to get better understanding −
def solve(s): res = "" cnt = 1 for i in range(1, len(s)): if s[i - 1] == s[i]: cnt += 1 else: res = res + s[i - 1] if cnt > 1: res += str(cnt) cnt = 1 res = res + s[-1] if cnt > 1: res += str(cnt) return res s = "abbbaaaaaaccdaaab" print(solve(s))
Input
"abbbaaaaaaccdaaab"
Output
ab3a6c2da3b
- Related Questions & Answers
- Program to perform prefix compression from two strings in Python
- C++ Program to Perform String Matching Using String Library
- Difference between Lossy Compression and Lossless Compression
- Python Support for bzip2 compression (bz2)
- Compression compatible with gzip in Python (zlib)
- Program to perform excel spreadsheet operation in Python?
- Enable MySQL Compression
- How to perform string matching in MySQL?
- Program to perform XOR operation in an array using Python
- Compression using the LZMA algorithm using Python (lzma)
- How To enable GZIP Compression in PHP?
- Data compression in SAP HANA
- PHP compression Stream Wrappers
- What is DjVu Compression?
- How to perform string aggregation/concatenation in Oracle?
Advertisements