Skip to main content
 首页 » 编程设计

python之我该如何结束这个循环

2025年01月19日13Leo_wl

我正在尝试按字母顺序计算字符串的最长长度

s = 'abcv' 
longest = 1 
current = 1 
for i in range (len(s) - 1): 
    if s[i] <= s[i+1]: 
        current += 1 
    else: 
        if current > longest: 
            longest = current 
            current = 0 
    i += 1 
print longest 

对于这个特定的字符串,'Current' 以正确的长度 4 结束,但从不修改 longest。

编辑:下面的代码现在遇到错误

s = 'abcv' 
current = 1 
biggest = 0 
for i in range(len(s) - 1): 
    while s[i] <= s[i+1]: 
        current += 1 
        i += 1 
    if current > biggest: 
        biggest = current 
    current = 0 
print biggest 

看来我的逻辑是正确的,但我遇到了某些字符串的错误。 :(

虽然互联网上有打印最长字符串的代码源,但我似乎找不到如何打印最长的字符串。

请您参考如下方法:

break将跳到循环后面(缩进为 for 语句。continue 将跳转到循环开始并进行下一次迭代

您在 else: 中的逻辑声明不起作用 - 您需要将其缩进少一个。


if s[i] <= s[i+1]: 

检查“实际字符是否小于或等于下一个字符”——如果是这种情况,您需要增加内部计数器,如果它更长则设置最长

您可能会遇到 if s[i] <= s[i+1]: 的麻烦- 你一直这样做到 len(s)-1 . "jfjfjf"是len("jfjfjf") = 6 - 你会从 0 迭代到 5 - 但 if 访问 s[5]和 s[6]这是更多的项目。


一种不同的方法,无需遍历显式索引并将其分为两个职责(获取按字母顺序排列的子字符串列表,将它们排在最前面):

# split string into list of substrings that internally are alphabetically ordered (<=) 
def getAlphabeticalSplits(s): 
    result = [] 
    temp = "" 
    for c in s: # just use all characters in s 
        # if temp is empty or the last char in it is less/euqal to current char 
        if temp == "" or temp[-1] <= c:  
            temp += c # append it to the temp substring 
        else: 
            result.append(temp) # else add it to the list of substrings 
            temp = "" # and clear tem 
    # done with all chars, return list of substrings 
    return result 
 
 
# return the splitted list as copy after sorting reverse by length 
def SortAlphSplits(sp, rev = True): 
    return sorted(sp, key=lambda x: len(x), reverse=rev) 
 
splitter = getAlphabeticalSplits("akdsfabcdemfjklmnopqrjdhsgt") 
print(splitter) 
sortedSplitter = SortAlphSplits(splitter) 
print (sortedSplitter) 
print(len(sortedSplitter[0])) 

输出:

['ak', 's', 'abcdem', 'jklmnopqr', 'dhs'] 
['jklmnopqr', 'abcdem', 'dhs', 'ak', 's'] 
9 

这一个返回拆分数组+按长度降序对它们进行排序。在关键环境中,这比你的内存消耗更多,因为你只缓存一些数字,而另一种方法填充列表并将其复制到排序的列表中。

要解决您的代码索引问题,请稍微更改您的逻辑: 从第二个字符开始,测试之前的字符是否小于这个字符。这样你将永远检查这个字符与之前的字符

s = 'abcvabcdefga' 
current = 0 
biggest = 0 
for i in range(1,len(s)): # compares the index[1] with [0] , 2 with 1 etc 
    if s[i] >= s[i-1]:    # this char is bigger/equal last char 
        current += 1 
        biggest = max(current,biggest) 
    else:  
        current = 1 
 
print biggest