- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to reverse words separated by set of delimiters in python
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:
Example
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: words.append("".join(g)) for k, g in groupby(sentence, lambda x: x in delimiters): if k: ans += "".join(g) else: ans += words.pop() return ans ob = Solution() s = "Computer/Network:Internet|tutorialspoint" delims = ["/", ":", '|'] print(ob.solve(s, delims))
Input
"Computer/Network:Internet|tutorialspoint", ["/", ":", '|']
Output
tutorialspoint/Internet:Network|Computer
Advertisements