I am confused why did you do it twice:

- Code: Select all
` if s[i]<s[i+1]:`

new+=s[i]

if s[i]<s[i+1]:

new+=s[i+1]

and what is this mysterious code

- Code: Select all
` else:`

new

supposed to do?

Anyhow: this is a very popular CS task ("longest increasing sequence" or "longest non-decreasing sequence"). I recommend to throw your code away and start afresh with clear design. Here are some ideas:

(@ mucseydel : I am actually more comfortable with indexes so I will do it with indexes).

So the goal is to find such indexes a,b into string s such that s[a:b+1] is the longest non-decreasing / increasing sequence. (Whether we'll finf non-decreasing or strictly increasing is the minor detail and will only depend on whether you use operator "<=" or "<" while comparing elements). OK.

a) consider that the answer is (0,0) : that is, the 1st symbol is the answer: nothing longer than that exists; -- assign it to some vars, like

- Code: Select all
`i,j = 0,0`

b) go over all chars of s between 1st and and next-to-last:

- Code: Select all
`for k in range(0, len(s)-1):`

...

c) if the character after k is greater (or >=) than the kth, we're increasing:

good, increase your j;

d) otherwise:

stopped increasing;

your current (i,j) might be the answer.

You also need to have another tuple (say (a,b) to keep the current longest substring: create is before the loop similar to i,j.

Now, if (b-a) < (j-i): you've found another maximum; store it in (a,b);

in any case, reset (i,j) to (k+1, k+1)

Try to implement it; don't hesitate to ask more questions if you're stuck.

NB: there is a corner-case... Let it surprise you.

Finally, here is how I would test it:

- Code: Select all
` ss = [`

("azcbobobeghakl", "begh" ),

("azcbobobegghakl", "beg" ),

("abcdeabcdefg", "abcdefg" ),

("abcdeabcdefga", "abcdefg" ),

("zyx", "z" ),

("zyxa", "z" ),

("zyxab", "ab"),

("a", "a" ),

("", "" ),

]

for s, expected in ss:

ans = longest_increasing_sequence(s)

print repr(s), repr(ans), ans == expected

assert(ans == expected)