问题描述
此代码适用于所有字符串,除了需要最后一个字符的字符串.
This code works fine for all the strings, except for the ones where the last char is needed.
s='abcdefghijklmnopqrstuvwxyz'
sub =''
test =s[0]
for n in range(len(s)-1):
if len(test) > len(sub):
sub = test
if s[n] >= s[n-1]:
test += s[n]
else:
test = s[n]
print 'Longest substring in alphabetic order is: ' + str(sub)
您如何建议这样做的可能性?
How do you suggest a possibility for doing this?
提前谢谢你们!
附注:
感谢到目前为止的答案.问题是,无论我输入哪个范围,我将打印的子变量都不会得到我想要的所有字符.循环在 :\ 之前完成,可能是程序本身的问题.
Thanks for the answers so far. The problem is that, no matter which range I type, the sub variable, which I will print, doesn't get all the chars I want. The loop finishes before :\ Maybe it's a problem with the program itself.
有什么额外的提示吗?:)
Any extra tips? :)
推荐答案
您的问题在于 range(len(s)-1)
.Range 生成一个列表,直到其上限参数 value-1,因此您不需要将 1 减去 len(s),使用:
Your problem is with range(len(s)-1)
. Range generates a list up to its upper limit parameter value-1 so you don't need to subtract1 to len(s), use:
range(len(s))
来自 https://docs.python.org/2/library/functions.html#range
范围(停止)范围(开始,停止[,步骤])这是一个多功能函数,用于创建包含等差数列的列表.它最常用于 for 循环.论据必须是纯整数.如果省略 step 参数,则默认为 1.如果省略 start 参数,则默认为 0.完整形式返回一个纯整数列表 [start, start + step, start + 2 *步, ...].如果 step 为正,则最后一个元素是最大的开始+ i * 步数小于停止;如果 step 为负,则最后一个元素是大于 stop 的最小 start + i * step.步长不能为零
另一方面,您将问题标记为 python2.7,所以我假设您使用的是 2.7.如果是这种情况,使用 xrange
而不是 range
会更有效,因为这样您将使用迭代器而不是生成列表.
On the other hand, you are labeling your question as python2.7 so I assume you are using 2.7. If that is the case, it is more efficient to use xrange
instead range
because that way you will use an iterator instead generating a list.
编辑
从对此问题的评论中,您可以将代码更改为:
From the comments to this question, you can change your code to:
s='caabcdab'
sub =''
test =s[0]
for i in range(1,len(s)+1):
n = i%len(s)
if len(test) > len(sub):
sub = test
if i >= len(s):
break
if s[n] >= s[n-1]:
test += s[n]
else:
test = s[n]
print 'Logest substring in alphabetic order is: ' + str(sub)
这篇关于按字母顺序排列的最长字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!