Why is the following Python code wrong?

I have the following problem for my assignment:

Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = azcbobobegghakl, then your program should print:

Longest substring in alphabetical order is: beggh

The code I wrote for the problem is this:

s = 'azcbobobegghakl'

current_index = 1
first_index = 0

result_string = ''
current_string = s[first_index]

while current_index < len(s):
    if ord(s[first_index]) <= ord(s[current_index]):
        current_string += s[current_index]
    elif ord(s[current_index]) < ord(s[first_index]):
        current_string = ''

    if len(current_string) > len(result_string):
        result_string = current_string[:]

    current_index += 1
    first_index += 1

print('Longest substring in alphabetical order is: ' + result_string)

The code doesn't give out the correct result, for some reason, it gives out eggh instead of beggh. And since this is an assignment, I do not ask that you give me the corrected code, but just give me an hint on where I am wrong since I wanna solve my problem BY MYSELF and don't wanna cheat.

Thanks.

Upvotes: 1

Views: 141

Answers (1)

zhangxaochen
zhangxaochen

Reputation: 33997

Error is here:

current_string = ''

you should not clear it when you find s[current_index]) < s[first_index].

Other hints:

  1. no need to use ord.
  2. what happens if s='a'?
  3. no need to copy result_string = current_string[:], since strings are immutables

Hints OVER ;P

Upvotes: 1

Related Questions