按字母顺序排列的最长字符串

2024-03-27 23:52:35 发布

您现在位置:Python中文网/ 问答频道 /正文

除了需要最后一个字符的字符串外,这段代码对所有字符串都适用。在

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) 

你怎么建议这样做的可能性?在

提前谢谢各位!在

附言:

谢谢你的回答。问题是,无论我输入哪个范围,我要打印的子变量都不能得到我想要的所有字符。循环在之前结束:\n可能是程序本身的问题。在

有什么额外的提示吗?:)


Tags: 字符串代码intestforlenlongestif
3条回答

enemurate而不是范围:

 s='abcdefghijklmnopqrstuvwxyz'

sub =''
test =s[0]

for n,value in enumerate(s):
    if len(test) > len(sub):
        sub = test
    if value >= s[n-1]:
        test += s[n]
    else:
        test = s[n]

您的问题在于range(len(s)-1)。不需要使用len-1来减去它的值,所以不需要使用len-1的上限值:

range(len(s))

来自https://docs.python.org/2/library/functions.html#range

range(stop) range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero

另一方面,您将问题标记为python2.7,所以我假设您使用的是2.7。如果是这样,那么使用xrange而不是range更有效,因为这样您将使用迭代器而不是生成列表。在

编辑

根据此问题的注释,您可以将代码更改为:

^{pr2}$

您可以使用以下代码:

s = 'abcdefgahijkblmnopqrstcuvwxyz'
sub = ''
test = s[0]

for index, character in enumerate(s):
    if index > 0:
        if character > s[index - 1]:
            test += character
        else:
            test = character
    if len(test) > len(sub):
        sub = test
print 'Longest substring in alphabetic order is: ' + str(sub)

还有几点建议。在

  1. Python字符串是iterable。i、 你可以在它们之间循环。在
  2. 当您希望在迭代列表的索引时使用enumerate。在

相关问题 更多 >