我该如何结束这个循环?

2024-09-30 23:36:08 发布

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

我试着按字母顺序数一数最长的字符串

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结束,但从不修改最长长度。你知道吗

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

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

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

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


Tags: 字符串代码inforlenlongestif顺序
3条回答

使用while条件循环,然后您可以很容易地定义在什么条件下完成循环。 如果您想长期使用QualityCode: While循环比中断更好,因为您可以在一个地方看到循环条件。在loopbody之间识别简单的中断通常更糟糕。你知道吗

break将跳转到循环后面(作为for语句跳转到sam缩进)。continue将跳转到循环的开头并执行下一次迭代

你在else:语句中的逻辑不起作用-你需要减少一个缩进。你知道吗


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

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

你可能会因为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

你必须删掉else语句。因为考虑电流刚好超过最长值的情况,即从current = 3 and longest =3,电流通过自身递增变成4。现在在这里,您仍然希望它进入if current > longest语句

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
longest = current
print longest

相关问题 更多 >