Jean Beaucamp Jean Beaucamp - 3 months ago 35
Python Question

Python word counter

I'm taking a Python 2.7 course at school, and they told us to create the following program:


Assume s is a string of lower case characters.

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

In the case of ties, print the first substring.

For example, if s = 'abcbcd', then your program should print

Longest substring in alphabetical order is: abc


I wrote the following code:

s = 'czqriqfsqteavw'

string = ''

tempIndex = 0
prev = ''
curr = ''

index = 0
while index < len(s):
curr = s[index]
if index != 0:
if curr < prev:
if len(s[tempIndex:index]) > len(string):
string = s[tempIndex:index]
tempIndex=index
elif index == len(s)-1:
if len(s[tempIndex:index]) > len(string):
string = s[tempIndex:index+1]
prev = curr
index += 1

print 'Longest substring in alphabetical order is: ' + string


The teacher also gave us a series of test strings to try:

onyixlsttpmylw
pdxukpsimdj
yamcrzwwgquqqrpdxmgltap
dkaimdoviquyazmojtex
abcdefghijklmnopqrstuvwxyz
evyeorezmslyn
msbprjtwwnb
laymsbkrprvyuaieitpwpurp
munifxzwieqbhaymkeol
lzasroxnpjqhmpr
evjeewybqpc
vzpdfwbbwxpxsdpfak
zyxwvutsrqponmlkjihgfedcba
vzpdfwbbwxpxsdpfak
jlgpiprth
czqriqfsqteavw


All of them work fine, except the last one, which produces the following answer:


Longest substring in alphabetical order is: cz


But it should say:


Longest substring in alphabetical order is: avw


I've checked the code a thousand times, and found no mistake. Could you please help me?

Answer

These lines:

        if len(s[tempIndex:index]) > len(string):
           string = s[tempIndex:index+1]

don't agree with each other. If the new best string is s[tempIndex:index+1] then that's the string you should be comparing the length of in the if condition. Changing them to agree with each other fixes the problem:

        if len(s[tempIndex:index+1]) > len(string):
           string = s[tempIndex:index+1]