Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
908 views
in Technique[技术] by (71.8m points)

string - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...