Search code examples
pythonpython-3.xbit-manipulationbitwise-operators

a pythonic way of doubling consecutive binary bits


I have a binary list as input, here is an example:- [0, 1, 0, 0, 1, 1, 1, 0, 1, 0]

I want to write a function that creates two scores. a score for the zeros and a score for the ones.

The scoring system is as follows: if two of the same numbers are next to each other, the score doubles in value each time. So if there are two ones next to each other that is valued as more than if they were separated by a zero. Two ones next to each other will be valued as 3. Three ones next to each other will be valued as 7, and so on. [1, 1]

score 1 2

Total = 1 + 2 = 3

[1, 1 ,1]

Score 1 2 4

Total = 1 + 2 + 4 = 7

So for example with the binary looking list above the total value of zeros is 1 + 1 + 2 + 1 + 1 = 6 (zeros total)

the total value of the ones is 1 + 1 + 2 + 4 + 1 = 9 (ones total)

Example 2: Input: [0,0,0,1,1,0,1,1]

Ones index 3 = 1, index 4 = 2, index 6 = 1, index 7 = 2 Ones Total = 1+2+1+2 = 6

Zeros index 0 = 1, index 1 = 2, index 2 = 4, Index 5 = 1 Zeros Total = 1+2+4+1 = 8

Example 3: input: [1,1,1,1] output: ones total = 1 + 2 + 4 + 8 = 15, zeros total = 0

Example 4: input: [0,0,0,0,1] output: zeros total = 1 + 2 + 4 + 8 = 15, ones total = 1

So input is a variable length list of ones and zeros Output is two totals, a total for the zeros, and a total for the ones.

Wondering if there is a fancy short bitwise approach to achieving this in the shortest pythonic code ?


Solution

  • How's that?

    from itertools import groupby
    input_list =  [0, 1, 0, 0, 1, 1, 1, 0, 1, 0]
    results = [0, 0]  # First value is zeros, second is ones
    for key, values in groupby(input_list):
        results[key] += (2**len(tuple(values))) - 1
    assert results == [6,9]