How to separate each sequence of equal numbers from a string?

Asked

Viewed 702 times

2

How do I split a number string? For example '233' to obtain ['2','33'].

Given values may vary, for example '44446' and give ['4444','6'] or '2345' and give ['2','3','4','5'].

That is, give split whenever the number is different.

1 answer

0


You have to think about how it’s done and write the code - should be able to do with regular expressions, or do in a single line 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 :-) - is also a didactic example of "not everything that can be done in a line must 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 the fact that Python strings have a very complete "strip" method - maybe it’s easier to read:

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 English it would be: "as long as there are elements in the line: ( take a (difference in current line size and line size by removing the digits equal to the first) and add this number of digits equal to the first to the answer; remove the first digit and the others equal to it) "

Note that it is only possible because strings have the method 'lstrip' which removes only on the left side of a string all the characters passed.

  • yes this gives everything well, but there would be a simpler way to do it??

  • The driver will do what you say - and in that case, you have to take it step by step. This solution is simple - you can make it look simpler, if I delete the variable "start" and use a false digit to start counting - I will update

  • 1

    Yes it’s better :) you’re right, it’s quite simple thank you !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.