簡體   English   中英

最長的字母 substring 不返回最后一個索引字符

[英]longest alphabetical substring not returning last index character

我正在嘗試自己學習 Python 並遇到一些問題。 誰能幫我理解為什么這段代碼不會 append 'z' 到 'temp' 或 'ls' 變量? 謝謝!

temp = ""
ls = ""

for i in range(len(s) - 1):
    if s[i] <= s[i+1]:
       temp += s[i]

    else:
        temp += s[i]
        if(len(temp) > len(ls)):
            ls = temp
        temp = ""
if len(temp) > len(ls):
    print ("Longest substring in alphabetical order is: " + str(temp))
else:
    print ("Longest substring in alphabetical order is: " + str(ls))

您提出的問題的最直接答案是“因為 for 循環中的range的 -1)。很難在這樣的for循環中訪問“上一個和當前”或“當前和下一個”,因為你總是必須處理迭代器中沒有前一個或下一個元素的“邊緣情況”。

這是做你想做的事情的更好方法:

input_string = "abcuiahduehjoahduflcpfghijklmnprstvz"

ls = ""
temp = ""
previous_c = ""

for c in input_string:
    if c >= previous_c:
        temp += c
    else:
        if len(ls) < len(temp):
            ls = temp
        temp = c
    previous_c = c

if len(ls) < len(temp):
    ls = temp

print("longest alphabetically-ordered substring is:")
print(ls)

我使用了與您的示例相同的變量名稱。 請注意我如何input_string c 請注意我如何不嘗試訪問上一個/最后一個字符,而是我有一個last_c變量來保存上一個循環迭代中最后看到的字符。 這個last_c最初分配給一個空字符串,因此它總是“小於”所有其他字符/字符串。

如果你真的想使用索引(你不應該),那么它看起來像這樣(非常非常相似):

input_string = "abcuiahduehjoahduflcpfghijklmnprstvz"

ls = ""
temp = ""
previous_c = ""

for i in range(len(input_string)):
    c = input_string[i]
    if c >= previous_c:
        temp += c
    else:
        if len(ls) < len(temp):
            ls = temp
        temp = c
    previous_c = c

if len(ls) < len(temp):
    ls = temp

print("longest alphabetically-ordered substring is:")
print(ls)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM