Skip to content
Advertisement

Grouping Binary Digits in Python

I have a binary number, how can I group the same digits in pairs and split the number on single zero?

For example:

1100000001111011011 11

[[11, 00, 00, 00], [11, 11], [11], [11, 11]]

Advertisement

Answer

You could use an iter of the string to compare the current character to the next one. If they are the same, add them to the current block; if they are different, the first one must be the odd zero, so add twice the one after that to the next block.

s = "110011000110011000001111111100"
res = [[]]
it = iter(s)
for c in it:
    if next(it) == c:
        res[-1].append(c+c)
    else:
        res.append([next(it)*2])

Or using regular expressions to (a) get blocks of repeated values, (b) split those into chunks:

import re
res = [re.findall(r"00|11", b) for b in re.findall(r"(?:00|11)+", s)]

Both ways, res is [['11', '00', '11', '00'], ['11', '00', '11', '00', '00'], ['11', '11', '11', '11', '00']]

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement