-2

Hello I have some number like this :

a = "00001"
b = "00011" 
c = "00111"  
d = "01001"
e = "10001"

and I would like something like this :

a = "00001" => "0000", "1"
b = "00011" => "000", "11"
c = "00111" => "00", "111"
d = "01001" => "0", "1", "00", "1"
e = "10001" => "1", "000", "1"

How can I do this to split this number ?

Thank you very much !

pierre
  • 9
  • Possible duplicate of [How to split strings into text and number?](https://stackoverflow.com/questions/430079/how-to-split-strings-into-text-and-number) Check out the answer, it can be adapted to your problem – Thomas Lang Oct 07 '19 at 17:31

3 Answers3

2

groupby is made for this.

import itertools

def groupthem(binary):
    """Groups binary 1s and 0s separately.

    >>> groupthem("00001")
    ["0000", "1"]
    >>> groupthem("00011")
    ["000", "11"]
    >>> groupthem("01001")
    ["0", "1", "00", "1"]
    """

    groups = itertools.groupby(binary)
    return [''.join(group) for _, group in groups]
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
0

Partitions a string into the desired sublists

def encode(s):
  result, prev = [], ''

  for v in s:
    if not prev or prev[-1] == v:
      # continue current pattern
      prev += v
    else:
      # pattern change
      result.append(prev)
      prev = v

  if prev:
    result.append(prev)
  return result

a = "00001"
b = "00011" 
c = "00111"  
d = "01001"
e = "10001"

for s in [a, b, c, d, e]:
  print(s, encode(s))

Output

00001 ['0000', '1']
00011 ['000', '11']
00111 ['00', '111']
01001 ['0', '1', '00', '1']
10001 ['1', '000', '1']
DarrylG
  • 16,732
  • 2
  • 17
  • 23
0

A beauty of Python is there are so many ways to accomplish the same task. Here is another method using regex.

I expanded your example to show it only works with 0 or 1.

import re

a = "00001"
b = "00011" 
c = "00111"  
d = "01001"
e = "10001"
f = "52255"
g = "90099"
h = "81811"

def parse(s):
    """Parse binary string into like groups."""
    f = re.findall('([0]+)|([1]+)', s)
    return [z if z else o for z, o in f]

for i in [a, b, c, d, e, f, g, h]:
    print(i, parse(i))

Output:

00001 ['0000', '1']
00011 ['000', '11']
00111 ['00', '111']
01001 ['0', '1', '00', '1']
10001 ['1', '000', '1']
52255 []
90099 ['00']
81811 ['1', '11']
S3DEV
  • 8,768
  • 3
  • 31
  • 42