最长字母子字符串,不返回最后一个索引字符

时间:2020-06-14 18:31:44

标签: python

我正在尝试自己学习Python并遇到一些问题。谁能帮助我理解为什么此代码未在“ temp”或“ ls”变量后附加“ z”?谢谢!

    yaml = YAML() 

1 个答案:

答案 0 :(得分:0)

您所问问题的最直接答案是“由于range循环中for的-1)。很难访问” previous and current”或“ current and像这样在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)

我使用了与您的示例相同的变量名。请注意,我如何遍历c中的每个字符input_string。请注意,我如何不尝试访问上一个/最后一个字符,而是使用一个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)
相关问题