python - How to return alphabetical substrings? -


i'm trying write function takes string s input , returns list of substrings within s alphabetical. example, s = 'acegibdh' should return ['acegi', 'bdh'].

here's code i've come with:

s = 'acegibdh' ans = [] subs = [] = 0 while != len(s) - 1:     while s[i] < s[i+1]:         subs.append(s[i])         += 1     if s[i] > s[i-1]:         subs.append(s[i])         += 1     subs = ''.join(subs)     ans.append(subs)     subs = [] print ans  

it keeps having trouble last letter of string, because of i+1 test going beyond index range. i've spent long time tinkering try , come way avoid problem. know how this?

why not hard-code first letter ans, , work rest of string? can iterate on string instead of using indices.

>>> s = 'acegibdh' >>> ans = [] >>> ans.append(s[0]) >>> letter in s[1:]: ...     if letter >= ans[-1][-1]: ...             ans[-1] += letter ...     else: ...             ans.append(letter) ... >>> ans ['acegi', 'bdh'] 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -