Python单词计数器 [英] Python word counter

查看:86
本文介绍了Python单词计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学校学习 Python 2.7 课程,他们告诉我们创建以下程序:

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

假设 s 是一串小写字符.

Assume s is a string of lower case characters.

编写一个程序,打印 s 中字母按字母顺序出现的最长子串.

Write a program that prints the longest substring of s in which the letters occur in alphabetical order.

例如,如果 s = azcbobobegghakl ,那么你的程序应该打印

For example, if s = azcbobobegghakl , then your program should print

按字母顺序排列的最长子串是:beggh

Longest substring in alphabetical order is: beggh

如果是平局,打印第一个子串.

In the case of ties, print the first substring.

例如,如果 s = 'abcbcd',那么你的程序应该打印

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

按字母顺序排列的最长子串是:abc

Longest substring in alphabetical order is: abc

我写了以下代码:

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:

按字母顺序排列的最长子串是:cz

Longest substring in alphabetical order is: cz

但它应该说:

按字母顺序排列的最长子串是:avw

Longest substring in alphabetical order is: avw

我检查了代码一千次,没有发现错误.你能帮我吗?

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

推荐答案

这些行:

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

彼此不同意.如果新的最佳字符串是 s[tempIndex:index+1] 那么这就是您应该比较 if 条件中的长度的字符串.将它们更改为彼此一致可以解决问题:

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]

这篇关于Python单词计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆