Need to write a program that prints the longest substring of variable, in which the letters occur in alphabetical order.
eg. s = 'onsjdfjqiwkvftwfbx', it should returns 'dfjq'.
as a beginner, code written as below:
y=()
z=()
for i in range(len(s)-1):
letter=s[i]
while s[i]<=s[i+1]:
letter+=s[i+1]
i+=1
y=y+(letter,)
z=z+(len(letter),)
print(y[z.index(max(z))])
However, above code will always return
IndexError: string index out of range.
It will produce the desired result until I change it to range(len(s)-3).
Would like to seek advice on:
Why
range(len(s)-1)will lead to such error message? In order to take care of index up to i+1, I have already reduce the range value by 1. my rationale is, if the length of variable s is 14, it has index from 0-13, range(14) produce value 0-13. However as my code involves i+1 index, range is reduced by 1 to take care of this part.How to amend above code to produce correct result. if
s = 'abcdefghijklmnopqrstuvwxyz', above code with range(len(s)-3) returnsIndexError: string index out of rangeagain. Why? what's wrong with this code?
Any help is appreciated~