Home > front end >  string pattern parsing and replacing the next aphabets
string pattern parsing and replacing the next aphabets

Time:06-08

suppose if we have a below string so we need to see the first consecutive repeated characters for example as aa and it shud be replaced the next alphabet word as b and then keep the remaining characters, similarly it should be repeated till we dont have the repeated characters as below

original string -------> aabcdghhjjk # the 'aa' are replaced by next in alphabet single 'b'
next output1 expected ->  bbcdghhjjk  
next output2 expected ->   ccdghhjjk
next output3 expected ->    ddghhjjk
next output4 expected ->     eghhjjk
next output5 expected ->      egijjk
next output6 expected ->       egikk 
next output7 expected ->        egil # end - no more duplicate letters

So what i tried so far is as below.

s="aabcdghhjjk"
prev=s[0]
count=1
maxcount=1
for i in range(1,len(s)):
    if s[i]==prev:
        count =1
        maxcount=max(maxcount,count)
print(maxcount)

output is 2 so i have got aa as 2 times but how do i replace this with next alphabet b?

CodePudding user response:

You haven't posted any code that does actally anything to modify the string - you are only counting letters that are doubled up.

To solve your thing you need to have "position" inside the string you are currently at, compare that letter with the next one (if next one there) - if same you need to splice the string, remove letters at pos,pos 1 and replace with the next letter of the alphabet at pos.

This would sove that:

s="aabcdghhjjk"

results = []
pos = 0
# modifying s (string == immuteable) is wasteful, could use list instead
while s:
    if len(s) < 2 or len(s) < pos 2:
        results.append(s)
        break

    # only add to results if not at results's last spot
    if not results or results[-1] != s:
        results.append(s)

    if s[pos] == s[pos 1]:       
        next_letter = chr(ord(s[pos]) 1)
        # replace stuff by list slicing, creates a new immuteable string
        s = s[:pos]   next_letter   s[pos 2:]
    else:
        # not equal letters, advance position in string
        pos  = 1
        
print(results)

Output:

['aabcdghhjjk', 
  'bbcdghhjjk', 
   'ccdghhjjk', 
    'ddghhjjk', 
     'eghhjjk', 
      'egijjk',  
      'egikk', 
       'egil']

There is still an edge-case where you could end up with doubled up letters in your words if you replace a letter later to something that combines with already evaluated positions to another double up.

Have fun fixing that edge case.

  • Related