Home > other >  Transform "4CA2CACA" to "CCCCACCACA"
Transform "4CA2CACA" to "CCCCACCACA"

Time:10-16

I have already tried this (as sombody told me on another question):

 import re
 def decode(txt):
     list = []
     for cnt, char in re.findall(r"([\d*])([^d])", txt):
         list.extend((char * (int(cnt) if cnt else 1)))
     list = "".join(list)
     return list

Example:

print(decode("2CACA2CACA3CACACA3CAC"))

This is what I get

CCCCCCCCCC

And this is what I need

CCACACCACACCCACACACCCAC

CodePudding user response:

What you are missing is characters without a digit in front. This will include those:

import re

def decode(txt):
    _list = []
    for cnt, char, single_char in re.findall(r"(\d)([^\d])|([^\d])", txt):
        if single_char:
            _list.extend(single_char)
        else:
            _list.extend((char * (int(cnt) if cnt else 1)))
    _list = "".join(_list)
    return _list

print(decode("2CACA2CACA3CACACA3CAC"))

CodePudding user response:

You can either use a one-liner like this:

>>> x = '2CACA2CACA3CACACA3CAC'
>>> "".join([x[idx 1]*(int(i)-1) if i.isnumeric() else i for idx, i in enumerate(x)])
'CCACACCACACCCACACACCCAC'

Or you could do it in a more verbose way:

>>> x = '2CACA2CACA3CACACA3CAC'
>>> string = ""
>>> for idx, i in enumerate(x):
...   if i.isnumeric():
...     string  = x[idx 1] * (int(i)-1)
...   else:
...     string  = i
...
>>> string
'CCACACCACACCCACACACCCAC'

This way, you don't have to import any libraries, or do full searches through the list.


Edit: Of course, I realize now that this is quite naïve, and only expects numbers between 1 and 9. If there are larger numbers than that, then the above code will not do what you want. It will also not work for zero.

  • Related