I am trying to figure out how to compare a character in a string to the next character in the string. For example, if I have a string:
s = \'vzcbotdebobeggg
How about this:
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))
Explanation:
matches
is a list of all substrings with "ascending" characters.current
is the substring of ascending characters being built as we iterate through the string. We start out with the first character of the string.enumerate()
helps us keep track of the index of the previous character (because the enumeration starts at 0
and we iterate the string from the second character onwards).This is less obvious, but seems to work:
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)