0

I'm using Python 2.7 and wants to find out is there a way to check if a given string contains at least 4 sequential numbers going up or down?

The only way I could come up with is to check every character and its 3 following characters to see if they are digits and then to see if the difference between each character is 1.

Is there another way doing it?

Thank you in advance!

itzick binder
  • 475
  • 7
  • 29
  • 2
    define numbers, this could be "ab12345cd" or "AB1011121314cD", e.g 1, 2, 3, 4 or 10 11 12 13, what I mean is do you intend to find NUMBERS or DIGITS – DrPrItay Oct 20 '16 at 11:37
  • There are almost certainly any number of ways to do it. You should post your code on the code review site. http://codereview.stackexchange.com/ – OrderAndChaos Oct 20 '16 at 11:37

1 Answers1

1
def has_sequence(s):
    """Returns sequence if found, empty list otherwise."""
    pos = 0
    stack = []
    while pos != len(s):
        try:
            val = int(s[pos])
        except ValueError:
            pos += 1
            stack = []
            continue

        if not stack:
            stack.append(val)
        elif stack[-1] + 1 == val:
            stack.append(val)
            if len(stack) == 4:
                return stack
        else:
            stack = []

        pos += 1

    return []