Simple data compression algorithm
Simple data compression algorithm is one of the programming question recently asked me in the interview, So I wanted to share it. happy coding and all the best.
PYTHON PROGRAM
Luminari
7/14/20241 min read
Question:
write a program for simple data compression algorithm
Example:
data = [1,2,3,4,0,0,0,3,4,6,0,0,0,21,2,3]
out = [1,2,3,4,"3x0",4,6,"2x0",21,2,3]
Logic:
Initialize comp_count to 1 and an empty list called result.
Iterate over the input list data (except for the last element).
If the current element is the same as the next element, increment comp_count.
If the current element is different from the next element:
If there were consecutive identical elements (i.e., comp_count > 1), append the count and the element to result.
Append the current element to result.
Reset comp_count to 1 for the next element.
Return the compressed list in the format “count x element”.
Solution in python:
# Example 1
data = [1,2,3,4,0,0,0,3,4,6,0,0,0,21,2,3]
out = [1,2,3,4,"3x0",4,6,"2x0",21,2,3]
# Example 2
data = [1, 1, 2, 2, 2, 3, 4, 4, 4, 4],
output would be ['2x1', '3x2', 3, '4x4']
Preparing for interview?
Checkout our Interview prep page, It might help you.
My interests
As a techie + proud Hindhu i love to know/write about technology, spiritual knowledge.
Hey!, I am not living library. But if there is topic if you want me to cover, I will do my research and write about it, if it is unfamiliar to me. Its fun to learn and grow together.
Contact ID
Contact
author@luminari.info
© 2024. All rights reserved.