开头,final 和 result 都指向 ['b', 'e', 'g', 'g', 'h'].after result += 'a' final 和 result 都指向 ['b', 'e', 'g', 'g', 'h', 'a'].现在输入了 elif 块,结果将指向一个新列表 ['a'],而 final 仍然指向 ['b', 'e', 'g', 'g', 'h', 'a'].final 在此之后将不再更新因此,您的原始代码(在编辑之前)可以通过更改来修复result += 字母 到result = result + [字母]:s = 'azcbobobegghakl'结果 = []最终 = []对于 s 中的字母:结果 = 结果 + [字母]如果 result == sorted(result) 和 len(result) >= len(final):最终=结果elif 结果 != 排序(结果):结果 = [结果[len(result)-1]]打印(最终)When executing my code for the given task, I keep getting the longest string plus the next letter in the iteration. For example, if I use s = 'azcbobobegghakl' I will get "beggha" as the longest string, when the answer is supposed to be "beggh". This same bug occurs for all strings of random letters I tried. I have figured out that the extra letter gets added on after the "result += letters" statement, but I'm not sure how to fix it. Here is my code:s = 'azcbobobegghakl'result = []final = []for letters in s: result += letters if result == sorted(result) and len(result) >= len(final): final=result elif result != sorted(result): result = [result[len(result)-1]]print "".join(final) 解决方案 The problem here is that result and final point to the same list.You are probably thinking that += will create a new list when you issue result += letters, but it won't:>>> x = [1,2]>>> y = x>>> x += [3]>>> x[1, 2, 3]>>> y[1, 2, 3]>>> x is yTrueHowever, when you use x = x + [3]:>>> x = [1,2]>>> y = x>>> x = x + [3]>>> x[1, 2, 3]>>> y[1, 2]>>> x is yFalseFor an explanation of this behavior, see this question. This is what's happening in your for loop (edit: of your original code) when letters is the last a character in your string:at the beginning, final and result both point to ['b', 'e', 'g', 'g', 'h'].after result += 'a' final and result both point to ['b', 'e', 'g', 'g', 'h', 'a'].now the elif block is entered and result will point to a new list ['a'], while final still points to ['b', 'e', 'g', 'g', 'h', 'a'].final will never be updated again after thisHence, your original code (before you edited it) can be fixed by changing result += letters to result = result + [letters]:s = 'azcbobobegghakl'result = []final = []for letters in s: result = result + [letters] if result == sorted(result) and len(result) >= len(final): final=result elif result != sorted(result): result = [result[len(result)-1]] print(final) 这篇关于在给定字符串中按字母顺序查找最长的字母子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-24 15:55