pythonstringnumberssequential-number

Check for sequential numbers in string in Python


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!


Solution

  • 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 []