You have to think how it's done and write the code -
must give to do with regular expressions, or
do in a line only with map / reduce techniques -
but the explicit code in some lines is well readable:
def separate_digits(line):
result = []
chain = ""
last_digit = None
for digit in line:
if last_digit != digit:
if chain:
result.append(chain)
chain = ""
chain += digit
last_digit = digit
result.append(chain)
return result
And this here is the form in a line with "reduce" - just for entertainment purposes :-) - there is also a didactic example of "not everything that can be done in a line should be done in a row "
reduce((lambda previous, digit: [digit] if not previous else (((previous.__setitem__(-1, previous[-1] + digit) if previous[-1][-1] == digit else previous.append(digit)), previous)[1]) ), list("44445552"), [])
update
Look, there's another way using Python's strings to have the complete strip method - maybe easier to understand readable:
def separate_strip(line):
result = []
while line:
digits = (len(line) - len(line.lstrip(line[0]))) * line[0]
result.append(digits)
line = line.lstrip(line[0])
return result
So, in Portuguese it would be: "as long as there are elements in the line:
(take the (difference in current line size and line size by removing
the digits equal to the first) and add these as many digits as the first to the answer; remove the first digit and the others equal it) "
Note that it is only possible because the strings have the 'lstrip' method, which removes all the last characters from the left side of a string.