I am trying to write a python program that will take any string of lowercase letters and return the longest alphabetical substring within it. Below is a segment of the code.
s="abc" #sample string
anslist=[] #stores answers
shift=0 #shifts substring
expan=0 #expands substring
while len(s) >= 1+shift+expan: #within bounds of s
if s[0+shift+expan] > s[1+shift+expan]: #if not alphabetical
shift += 1 #moves substring over
else: #if alphabetical
while s[0+shift+expan] <= s[1+shift+expan]: #while alphabetical
expan += 1 #checks next letter
anslist += s[0+shift:2+shift+expan] #adds substring to ans
expan = 0 #resets expansion
When I run the code, the line containing while s[0+shift+expan] <= s[1+shift+expan]: creates an error that the string index is outside of the range. I see that adding to expan will put the index out of range, but shouldn't the largest while loop solve this? I appreciate any help.
len(s) > 1+shift+expansince len will be 1 greater than the last 0 based index?shas a len of3but you can only index it up to 2 since the maximum index islen(object) - 1andshift + expan > 0.s[0+shift+expan] <= s[1+shift+expan]is true for b and c so then expan is +=1 and that goes out of range, you should add a check likeand expand+1+1+shift<len(s)