Ive been working on a question to find the longest substring in alphabetical order from a given string. I have a lot of experience in C++ but am absolutely new to python. Ive written this code
s = raw_input("Enter a sentence:")
a=0 #start int
b=0 #end integer
l=0 #length
i=0
for i in range(len(s)-1):
j=i
if j!=len(s)-1:
while s[j]<=s[j+1]:
j+=1
if j-i>l: #length of current longest substring is greater than stored substring
l=j-i
a=i
b=j
print 'Longest alphabetical string is ',s[i:j]
But I keep on getting this error
Traceback (most recent call last):
File "E:/python/alphabetical.py", line 13, in <module>
while s[j]<=s[j+1]:
IndexError: string index out of range
What am I doing wrong here? Again, I am very new to python!
while s[j]<=s[j+1]:
j+=1
Can run off the end of the string.
Try:
while j!=len(s)-1 and s[j]<=s[j+1]:
j+=1
Also think about what it means when you find the end of a sequence that's alphabetical - is there any reason to check for a longer sequence starting at some position later within that sequence?