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
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.
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.
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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With