Итак, мне было поручено подсчитать самую длинную подстроку в строке, в которой буквы располагаются в алфавитном порядке.Я пришел с ответом, который работает и является правильным, но, честно говоря, у меня проблемы с пониманием моего собственного кода ... пожалуйста, потерпите меня.Я обошел свое недоразумение, чтобы создать рабочий код.Почему в этом примере переменная longest
== 4 вместо 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)