Comparing characters in a string sequentially in Python

I am trying to figure out how to compare a character in a string with the next character in a string. For example, if I have a line:

s = 'vzcbotdebobeggglakyl'

I want to be able to compare the first character with the second character, and if the second character is greater than or equal to the first character (in alphabetical order, <b, g> e, y = y, etc.) I want to add 1 to another variable (basically a counter). If it is not, I want to reset the counter to 0. And basically repeat the whole process for the length of the string. If the counter becomes larger than the maxlen variable, add it to maxlen (or make maxlen = sublen). My attempt so far (and I think it works):

s = 'vzcbotdebobeggglakyl'
sublen = 1
maxlen = 0
startnum = 0
for char in s:
    stopnum = startnum + 1
    if stopnum < len(s):
        charone = s[startnum]
        chartwo = s[stopnum]
        if charone <= chartwo:
            sublen += 1
            startnum += 1
            if sublen > maxlen:
                maxlen = sublen
        else:
            startnum +=1
            sublen = 1
    else:
        sublen = 0
print 'Longest substring is', maxlen, 'characters.'

, , . . , , . ,

Longest substring is begggl, which is 6 characters.
+4
2

:

def longest_ascending(s):
    matches = []
    current = [s[0]]
    for index, character in enumerate(s[1:]):
        if character >= s[index]:
            current.append(character)
        else:
            matches.append(current)
            current = [character]
    matches.append(current)
    return "".join(max(matches, key=len))

:

  • matches - "" .
  • current - , . .
  • . enumerate() ( 0, ).
  • " " , .
  • , .
  • .
+1

, , , :

seq = "vzcbotdebobeggglakyl"

import itertools
result = max(
    (
        list(next(sub)) + [b for a, b in sub]
        for ascending, sub in itertools.groupby(zip(seq,seq[1:]), lambda x: x[0] <= x[1])
        if ascending
    ),
    key=len
)

print ''.join(result)
+2

All Articles