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,”3×0″,4,6,”2×0″,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,”3×0″,4,6,”2×0″,21,2,3]
# Example 2
data = [1, 1, 2, 2, 2, 3, 4, 4, 4, 4],
output would be [‘2×1’, ‘3×2’, 3, ‘4×4’]
Preparing for interview?
-
Checkout our Interview prep page, It might help you.