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:

JavaScript

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.

JavaScript

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

JavaScript

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