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)