Program to reverse words separated by set of delimiters in python

PythonServer Side ProgrammingProgramming

Suppose we have a string and a set of delimiters, we have to reverse the words in the string while the relative ordering of the delimiters should not be changed.

So, if the input is like s = "Computer/Network:Internet|tutorialspoint" delims = ["/", ":", '|'], then the output will be tutorialspoint/Internet:Network|Computer

To solve this, we will follow these steps:

words := a new list

ans := blank string

temp := a map where

Separate the words except the delimiter characters and insert them into words array

separate words when the character is in delimiter then add them into ans,

otherwise read word from words array reversely and add into ans

return ans

Let us see the following implementation to get better understanding:


Live Demo

from itertools import groupby
class Solution:
   def solve(self, sentence, delimiters):
      words = []
      ans = ""

      for k, g in groupby(sentence, lambda x: x in delimiters):
         if not k:

      for k, g in groupby(sentence, lambda x: x in delimiters):
         if k:
            ans += "".join(g)
            ans += words.pop()
      return ans

ob = Solution()
s = "Computer/Network:Internet|tutorialspoint"
delims = ["/", ":", '|']
print(ob.solve(s, delims))


"Computer/Network:Internet|tutorialspoint", ["/", ":", '|']


Updated on 26-Nov-2020 07:16:15