How to check if 3 characters match in sequential alpha order

Just curious, what is the most Pythonic / efficient way to determine if a 3 character sequence is in a sequential alpha order?

Below is a quick and dirty way that seems to work, other, more enjoyable implementations?

I believe that one alternative approach could be to sort a copy of the sequence and compare it with the original. No, this is not taken into account for spaces in the sequence.

(This is not homework - NPR Sunday Morning progam students 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 
+6
source share
5 answers

Easy:

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

Alternatively, you can use string.find() .

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

I assume that a function using this would look like this:

 def checkSequence(*letters): return ''.join(letters).lower() in ascii_lowercase 
+11
source

Here's a good pythonic way to check that for arbitrarily long sequences of characters:

 def consecutive_chars(l): return all(ord(l[i+1])-ord(l[i]) == 1 for i in range(len(l)-1)) 
+5
source
 ord('a') < ord(a)+1 == ord(b) == ord(c)-1 < ord('z') 
+4
source

It can be done just like

 >>> x=['a','b','c'] >>> y=['a','c','b'] >>> z=['c','b','a'] >>> x==sorted(x) or x == sorted(x,reverse=True) True >>> y==sorted(x) or y == sorted(y,reverse=True) False >>> z==sorted(x) or z == sorted(z,reverse=True) True >>> 

Think so. Letters are consecutive if they are sorted either ascending or descending.

As stated in the comment, since this will not work if the sequence contains holes, a different approach would be

 >>> ''.join(x).lower() in string.lowercase True >>> 
+4
source

How about something like this:

 l = letters.lower() if len(l)>=3 and ord(l[0])+2==ord(l[1])+1==ord(l[2]): print "yes" else: print "no" 
+1
source

Source: https://habr.com/ru/post/912691/


All Articles