Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if 3 characters are in consecutive alpha order

Just curious, what's the most pythonic/efficient way to determine if sequence of 3 characters are in consecutive alpha order?

Below a quick&dirty way that seems to work, other, nicer implementations?

I suppose one alternative approach might be to sort a copy the sequence and compare it with the original. Nope, that wouldn't account for gaps in the sequence.

(This is not homework - listeners to NPR Sunday Morning progam will know)

def checkSequence(n1, n2, n3):
    """ check for consecutive sequence of 3 """
    s = ord('a')
    e = ord('z')

#   print n1, n2, n3
    for i in range(s, e+1):
        if ((n1+1) == n2) and ((n2+1) == n3):
           return True

    return False


def compareSlice(letters):
    """ grab 3 letters and sent for comparison """

    letters = letters.lower()
    if checkSequence(ord(letters[0]), ord(letters[1]), ord(letters[2])):
        print '==> seq: %s' % letters
        return True

    return False
like image 323
Levon Avatar asked Apr 08 '12 15:04

Levon


People also ask

How do you find consecutive letters in C++?

Function maxRepeating(char str[], int n) takes two input parameters. The string itself, its size. Returns the character with the longest consecutive repetitions sequence. Traverse the string in str[] from 1st position till last.

What is consecutive characters?

adjective. following one another in uninterrupted succession or order; successive: six consecutive numbers, such as 5, 6, 7, 8, 9, 10. marked by logical sequence. Grammar.


2 Answers

Easy:

>>> letters = "Cde"
>>> from string import ascii_lowercase
>>> letters.lower() in ascii_lowercase
True
>>> letters = "Abg"
>>> letters.lower() in ascii_lowercase
False  

Alternatively, one could use string.find().

>>> letters = "lmn"
>>> ascii_lowercase.find(letters) != -1
True

I guess a function using this would look like:

def checkSequence(*letters):
    return ''.join(letters).lower() in ascii_lowercase
like image 101
Joel Cornett Avatar answered Sep 18 '22 14:09

Joel Cornett


Here's a nice pythonic way to check that for arbitrarily long sequences of chars:

def consecutive_chars(l):
    return all(ord(l[i+1])-ord(l[i]) == 1 for i in range(len(l)-1))
like image 34
Yuval Adam Avatar answered Sep 17 '22 14:09

Yuval Adam