小编Dae*_*lus的帖子

Python 3:完美的字母顺序

代码的目标是找到字符串中最长的字母子字符串.

s = 'xyzbcdezzz'
longest_string = ''
current_string = ''
stringcount = 0

for n in range (len(s) - 1):
    if s[n] <= s[n+1]:
        current_string += (s[n]+s[n+1])
        stringcount += 1
        print('current string:', stringcount, current_string)


    elif s[n] > s[n+1]:
        if len(current_string) > len(longest_string) :
            longest_string = current_string
            current_string = ''
            stringcount = 0
            print('the longest string checked is:', longest_string, ', count reset')

if len(current_string) == len(longest_string):
    print (current_string, longest_string)
if len(current_string) > len(longest_string):
    print (current_string)
if len(longest_string) > len(current_string):
    print(longest_string)
Run Code Online (Sandbox Code Playgroud)

当我运行这段代码时,它将'abbccd'作为最长的子字符串,当它实际上是'abcd'时.这是因为它检查字符a,将其与序列中的下一个进行比较,然后将a添加到b给出"ab".然后它检查b,与c比较并将bc加在一起,然后将"bc"添加到"ab". …

python string for-loop python-2.7 python-3.5

16
推荐指数
4
解决办法
2056
查看次数

标签 统计

for-loop ×1

python ×1

python-2.7 ×1

python-3.5 ×1

string ×1