So far i've got :
s = 'azcbobobegghakl'
i = 0
j = 1
temp = '' #temporary variable I use to change longest
longest = ''
for b in range(len(s)):
if s[i] <= s[j]: #checks if it's in alphabetical order
temp+=s[i]
if len(longest) < len(temp):
longest = temp
else:
temp = '' #reset temp after every substring
if len(longest) < len(temp):
longest += temp #update longest if the new substring is longer
i +=1
if j < len(s) - 1 : # because otherwise i get an IndexError
j +=1
print('Longest substring in alphabetical order is:', longest)
Now my problem is that I always get the correct string BUT without the last letter . (for example here instead of "beggh" i get "begg").
I also have to make it so that if it's a tie, the first one counts as the longest (if s = abcbcd, abc should be the longest )
And lastly I know this question has been asked several times here already but i want to fix the code I came up with if possible, not just use someone else's code entirely.
You aren't taking the current character into account if you find the next character isn't in alphabetical order, and that's why you're missing one character in the end.
Instead, you should always process the current character first before resetting temp
if the next character isn't in order.
s = 'azcbobobegghakl'
i = 0
temp = '' #temporary variable I use to change longest
longest = ''
for i in range(len(s)-1):
temp += s[i]
if len(longest) < len(temp):
longest = temp
if s[i] > s[i+1]: #checks if it's in alphabetical order
temp = '' #reset temp after every substring
if len(longest) < len(temp):
longest += temp #update longest if the new substring is longer
i +=1
print('Longest substring in alphabetical order is:', longest)
This outputs:
Longest substring in alphabetical order is: beggh