'Compress Binary Data Array

I have an array of size 2N where N[i]={0,1}, i.e each value in the array is either 0 or 1, How can I compress it to an array of size N? output array has the same property i.e each value in the array is either 0 or 1?

def compress(data):
    code = [0] * 10
    i = 0
    count_o = 0
    count_z = 0

    for e in range(0, len(data), 2):
        code[i] = data[e]
        i += 1

    for e in range( 1, len(data), 2):
        if data[e] == 0:
            count_z += 1
        else:
            count_o += 1
    code[9] = 1 if count_z < count_o else 0

  
    return code


def decode(code):
    data = [0] * 20
    i = 0

    for c in code:
        data[i] = c
        if i > 0:
            data[i - 1] = code[9]
     
        i += 2

    return data

I tried a lossy method where I take every alternate data point and for the rest take the maximum frequency.

After encoding the solution, I decode the same and compare it with the original data where each correct match is +1

On calling this function for different permutations of data the average I get is around 15.42.

The solution need not be a lossless solution, the best possible in the average scenario.



Solution 1:[1]

I hope this is what you are looking for:

arr=[1,0,0,1,1,0,0,1]
new_arr=[]
convB_N={(0,1):1,(0,0):0,(1,0):2,(1,1):3}
for i in range(0,len(arr),2):
    bi=(arr[i],arr[i+1])
    new_arr.append(convB_N[bi])
print(new_arr)

Output:

[2, 1, 2, 1]

This is simple binary to decimal. Take two input from array and return its corresponding decimal.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kalyan Reddy