Home > Net >  How to update an binary values array if the distance between two same values is less than 5?
How to update an binary values array if the distance between two same values is less than 5?

Time:03-07

I am jumbling with one usecase in python coding.

Question:

I have an array having binary values like [0,0,0,0,1,0,0,1,0,1,0,0,0,0,0,1,0,1,1,1,0,0,0,0,1,1]. Now I have to replace all the values by 1 in between two ones (1's) if the distance between them (1's) is less than 5.

For example, The index of the first 1 is 4 and the index of the second times occurrence of 1 is 7, so the distance between these two occurrences of 1's is 3 which is less than 5 (as per condition) therefore, We will replace all the values in between these two ones by 1.

Similarly, we have to do it for each value of the array.

Example : [0,0,0,0,1,0,0,1,0,1,0,0,0,0,0,1,0,1,1,1,0,0,0,0,1,1]

Desired output :

[0,0,0,0,1,**1,1**,1,**1**,1,0,0,0,0,0,1,**1**,1,1,1,**1,1,1,1**,1,1]

CodePudding user response:

def insert_ones(bit_stream):
    new_bit_stream = bit_stream.copy()
    last_one_idx = -1
    for idx, bit in enumerate(bit_stream):
        if last_one_idx == -1:
            if bit == 1:
                last_one_idx = idx
        else:
            if bit == 1:
                length = idx - last_one_idx
                if length < 6:
                    new_bit_stream[last_one_idx : idx] = [1] * length
                last_one_idx = idx
    return new_bit_stream

You can replace new_bit_stream with bit_stream if you want to mutate the stream in place

  • Related