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 = \'azcbobobeggh
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 y
True
However, when you use x = x + [3]:
>>> x = [1,2]
>>> y = x
>>> x = x + [3]
>>> x
[1, 2, 3]
>>> y
[1, 2]
>>> x is y
False
For 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:
final and result both point to ['b', 'e', 'g', 'g', 'h'].result += 'a' final and result both point to ['b', 'e', 'g', 'g', 'h', 'a'].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)