So I was assigned a tasks of counting the longest substring in a string in which the letters occur in alphabetical order. I came up with an answer that works and is correct but to be frank, I'm having trouble understanding my own code.. please bear with me. I worked around my misunderstanding to produce working code. Why, in this example, would the variable longest == 4 instead of 5?
s = 'azcbobobegghakl'
count = 0
longest = 0
end = 0
for a in range(len(s) - 1):
if s[a] <= s[a + 1]: # is s[a] greater than or = to the next char in string?
count += 1 # if it is, +1 to count
if count > longest: # if count is greater than longest (longest is current longest - 1), continue, otherwise keep counting
longest = count # new longest is the current count because it is longest
end = a + 1 # since end is in this if block, it counts the iteration where count was last greater than the longest
else: # when count is never greater than longest again the longest will be the length of the longest string
count = 0
start = end - longest
"""
end is the last position in the longest string (here it is 11 or h)
longest is length of the string (here it is 4)
so the end - longest characters = the start of string which is 7 or b
"""
print('Longest substring in alphabetical order is: ' + s[start:end + 1])
#prints the letters in s from position 7 to 11 + 1 (+1 because end = index 11 but it goes up to and not including 11)