
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reverse Vowels of a String in Python
Suppose we have a lowercase string. Our task is to reverse the vowels present in the string. So if the string is “hello”, then the string after vowel reversal will be “holle”. For string “programming”, it will be “prigrammong”
To solve this, we will follow these steps −
- Take the string and make a list of vowels, and store their indices as well
- reverse the vowel list
- set idx := 0
- for i := 0 to length of given string – 1
- if i is in index list −
- put vowels[i] into final string
- idx := idx + 1
- otherwise put string[i] into final string
- if i is in index list −
- return the list as a string
Example
Let us see the following implementation to get better understanding −
class Solution: def reverseVowels(self, s): chars = list(s) index = [] vowels = [] for i in range(len(chars)): if chars[i] in ['a','e','i','o','u']: vowels.append(chars[i]) index.append(i) vowels = vowels[::-1] final = [] ind = 0 for i in range(len(chars)): if i in index: final.append(vowels[ind]) ind += 1 else: final.append(chars[i]) str1 = "" return str1.join(final) ob1 = Solution() print(ob1.reverseVowels("hello")) print(ob1.reverseVowels("programming"))
Input
"hello" "programming"
Output
holle prigrammong
Advertisements