Skip to content Skip to sidebar Skip to footer

How To Return Alphabetical Substrings?

I'm trying to write a function that takes a string s as an input and returns a list of those substrings within s that are alphabetical. For example, s = 'acegibdh' should return ['

Solution 1:

Why not hard-code the first letter into ans, and then just work with the rest of the string? You can just iterate over the string itself instead of using indices.

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

Solution 2:

s = 'acegibdh'
ans = []
subs = []
subs.append(s[0])
for x in range(len(s)-1):
    if s[x] <= s[x+1]:
        subs.append(s[x+1])
    if s[x] > s[x+1]:
        subs = ''.join(subs)
        ans.append(subs)
        subs = []
        subs.append(s[x+1])
subs = ''.join(subs)
ans.append(subs)
print ans 

I decided to change your code a bit let me know if you have any questions

Solution 3:

Just for fun, a one line solution.

>>> s='acegibdh'>>> [s[l:r] for l,r in (lambda seq:zip(seq,seq[1:]))([0]+[idx+1for idx inrange(len(s)-1) if s[idx]>s[idx+1]]+[len(s)])]
['acegi', 'bdh']

Solution 4:

You should try to avoid loops that increment the position by more than one char per iteration.

Often it is more clear to introduce an additional variable to store information about the previous state:

s ='acegibdh'
prev =None
ans = []
subs = []
for ch in s:
    if prev isNoneor ch > prev:
        subs.append(ch)
    else:
        ans.append(''.join(subs))
        subs = [ch]
    prev = ch
ans.append(''.join(subs))

I think this read more straight forward (if there is no previous character or it's still alphabetical with the current char append, else start a new substring). Also you can't get index out of range problems with this approch.

Solution 5:

More than one while loop is overkill. I think this is simpler and satisfies your requirement. Note, this fails on empty string.

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

Post a Comment for "How To Return Alphabetical Substrings?"