python - run length encode / decode

  编 / 解码:

def rle(s):
    c = ''
    p = ''
    x = 1
    for _ in s:
        if _ == p:
            x += 1
        else:
            c += str(x)
            c += p
            x = 1
        p = _
    c += str(x)
    c += p
    return c[1:]


def rld(s):
    r = ''
    n = 0
    for _ in s:
        if _.isdigit():
            n = int(_)
        elif n > 0:
            r += _ * n
    return r


s = 'aaaaaaassssssssgggrrrttaawefw'
e = rle(s)
print(e)

  输出:

7a8s3g3r2t2a1w1e1f1w

  

猜你喜欢

转载自www.cnblogs.com/darkchii/p/12757841.html