-5

I am a beginner and am trying to write a piece of code that tells you how long the longest substring is that is written in alphabetic order.

So far I have:

    s = 'azcbobobegghakl'
    n=len(s)
    i=0
    longest=1


    while i<n+1:
        print(s[i])
        if s[i] < s[i+1]:
            longest+=1
            i+=1
        else:
            i+=1

    print(longest)

However I keep getting an error:

IndexError: string index out of range

Could somebody please tell me where I am going wrong and how to fix it

Roshan
  • 905
  • 9
  • 21
Nav Hari
  • 29
  • 1

4 Answers4

2

Try this:

s = 'azcbobobegghakl'
n=len(s)

longest=1
counter=1

for i in range(len(s)-1):
    print(s[i])
    if s[i] < s[i+1]:
        counter+=1
    else:
        if counter > longest:
            longest = counter
        counter = 1
if counter > longest:
     longest = counter

print(longest)
johk95
  • 873
  • 10
  • 28
1

Change your condition in while loop like this

Change

 while i < n-1:

  Change n+1 to n-1

Reason:

   n is length of string
   Index of string : 0,1,.....,n-1
   In your program one iteration  will check next element also:
    ie:  when I == 0 , it will access str[0], str[1]
    Like i == n - 2 , str[n-2], str[n-1]
    Now if your condition is i less than n +1 then it will check 
    i == n , str[n], str[n+1] it will give you index out of range 
    because str[n+1] doesn't exist
suhail areekkan
  • 1,646
  • 1
  • 13
  • 16
  • Error is in line `if s[i] < s[i+1]:` so if condition in while loop is `i < n` then in last iteration `i` will be equal to `n-1` and it will still throw index error in if condition in `s[i+1]` . – ands Aug 25 '17 at 22:27
0

Error that you are getting is IndexError: string index out of range in line 11 if s[i] < s[i+1]:. The problem is that i in while loop will become too big (bigger than n-1). Your loop condition should be while i<n-1: and NOT while i<n-1: like others have suggested in their answers. You are checking for each character in string s if it is smaller (if it appears before in alphabet, actually, Python check if it has a smaller Unicode code, so you need to use only lowercase or only uppercase letters) than the next character in the string. And you can check this for all characters in a string except the last one because the last character doesn't have successor (there is no next character after last one). That's why you should have i<n-1: in your while loop.

Full working code:

s = 'azcbobobegghakl'
n=len(s)
i=0
longest=1
print(n)


while i<n-1:
    print(s[i])
    if s[i] < s[i+1]:
        longest+=1
        i+=1
    else:
        i+=1

print(longest)
ands
  • 1,926
  • 16
  • 27
0

try this:

s = 'azcbobobegghakl'
n=len(s)
i=0
longest=1

while i<n:
    print(s[i])
    if i == n-1:
       break
    elif s[i] < s[i+1]:
       longest+=1
       i+=1
    else:
       i+=1

print(longest)