itzick binder itzick binder - 1 year ago 180
Python Question

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!

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

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

        pos += 1

    return []
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download