def f(s):
    if s == "":
        return s
    elif len(set(s)) == 1:
        return s[0]
    n = len(s) // 2
    l, r = s[:n], s[n:]
    return f"[{f(l)}{f(r)}]"

def g(s, k):
    if s == "":
        return ""
    elif len(s) == 1:
        return s * k
    else:
        st = s[1: -1]
        n = k // 2
        l, r = cut(st)
        return g(l, n) + g(r, k - n)
        
def encode(s):
    r = f(s)
    return f"{len(s)},{r}" if len(s) else ""

def cut(s):
    if s[0] != '[':
        return s[0], s[1:]
    else:
        i, c = 1, 1
        while i < len(s) and c > 0:
            if s[i] == ']':
                c -= 1
            elif s[i] == '[':
                c += 1
            i += 1
    return s[:i], s[i:]
    
def decode(s):
    if s == "":
        return ""
    k, st = s.split(',')
    return g(st, int(k))
    
for s in ("", "x", "xx", "xyy", "xyyy", "xxxxyyyy", "111112222", "Codewars"):
    print(encode(s))
    
for s in ("", "1,x", "2,x", "3,[xy]", "4,[[xy]y]", "8,[xy]", "9,[1[[12]2]]", "8,[[[Co][de]][[wa][rs]]]"):
    print(decode(s))

Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: