Home > Net >  'fill in' the missing position in a list with zeros
'fill in' the missing position in a list with zeros

Time:12-31

Here's part of the code I am working on:

def count_flip(string, init = '0'):
    x0 = init   string
    return sum(x != y for x, y in zip(x0, x0[1:]))

def absorb_counts(results):
    flip_counts = Counter()
    for binary_string, value in results.items():
        flip_counts[count_flip(binary_string)]  = value
    return [v for _, v in sorted(flip_counts.items())]

The input of absorb_counts, results, is a dictionary whose keys are binary strings, and values are some integers. This function combines all the values with the same 'flip' in the keys and sorts them in ascending order in the output. For example:

>>> test = {'011': 11, '111': 11, '110': 13, '100': 31, '001': 9, '000': 738, '010': 118, '101': 93}
>>> absorb_counts(test)
[738, 31, 162, 93]

The four numbers are 738 (0 flip), 31 (1 flip), etc. (There's an extra '0' in the front, given by count_flip.)

Question: Sometimes my input results doesn't have all the possible binary strings. In such cases, the output is a reduced list with missing positions. For example:

>>> test_1 = { '110': 13, '100': 31, '000': 738, '010': 118, '101': 93}
>>> absorb_counts(test_1)
[738, 162, 93]

How can I 'fill in' zeros in such positions? The output, in this case, would be [738, 0, 162, 93].

CodePudding user response:

You could iterate through range(int(max(results), base=2)) and initialize all the corresponding keys before you start accumulating the counts. If you do this, you don't even need Counter since you're starting off with a dict of zeroes:

def absorb_counts(results):
    flip_counts = {
        count_flip(bin(i)[2:]): 0
        for i in range(int(max(results), base=2))
    }
    for binary_string, value in results.items():
        flip_counts[count_flip(binary_string)]  = value
    return [v for _, v in sorted(flip_counts.items())]
  • Related