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
andfinal
point to the same list. You are probably thinking that+=
will create a new list when you issueresult += letters
, but it won't:However, when you use
x = x + [3]
:For an explanation of this behavior, see this question. This is what's happening in your
for
loop (edit: of your original code) whenletters
is the lasta
character in your string:final
andresult
both point to['b', 'e', 'g', 'g', 'h']
.result += 'a'
final
andresult
both point to['b', 'e', 'g', 'g', 'h', 'a']
.elif
block is entered and result will point to a new list['a']
, whilefinal
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]
:You've got a couple items to address. The first is that when you use...
This is not just assigning the values in result to final. It points the variable 'final' to the memory address containing the list that 'result' is also pointing to. So then if result is changed, so is final. To assign the values in result, use...
which will give you the values of a slice of the list from beginning to end. Or you can use...
After that change, you'll need to remove the length comparison in your elif statement.
Edited code: