On the construction of an algorithm for serial length compression of strings

Viewed 30

Repeat until string s is empty.

If there are two or more consecutive letters from the beginning of s

・Define n as the number of consecutive pieces.
・Display 'ns' and delete n characters from the beginning.

If two or more characters are not consecutive

・Memorize how many characters are not consecutive and display '-ns'.
・Then remove ns from the string.

Example.

input = 'abcaaaaaaaaaaaaaab'
output = '-3abc12a-1b'

input = 'AaAaAAAAa'
output = '-4AaAa4A-1a'

If you are familiar with the algorithm, it would be helpful to know.

1 Answers

I would use a regular expression to identify the different chunks of the string, and then use the re.sub callback to format the chunk as specified:

import re

regex = re.compile(r"(.)\1+|(?:(.)(?!\2))+")

def encode_match(match):
    a, b = match.group(0, 1)
    return f"{'-' * (not b)}{len(a)}{b or a}"

def encode(s):
    return regex.sub(encode_match, s)

print(encode('abcaaaaaaaaaaaab')) # '-3abc12a-1b'
print(encode('AaAaAAAAa'))        # '-4AaAa4A-1a'
Related