Python Program to Reverse consonants in a given string without affecting the other elements
Given a string, the task is to write a Python program to reverse only the consonants of a string without affecting the other elements’ positions.
Examples:
Input : hello
Output : lelho
Explanation: h,l,l are consonants in the given string. After modifying the string their occurrences are l,l,h and vowels positions are not changed.
Approach:
- Convert the string into a list of characters.
- Maintain another Python list for storing consonants.
- If the current element is consonant then append the current element to the consonant list.
- Start traversing the list again and replace the consonants with the element present in the consonant list from last.
- Finally, convert the list into a string and return it.
Implementation
Below is the implementation of the above approach.
Python3
# Function to check element is consonant or not def isConsonant(i): vow = [ 'a' , 'e' , 'i' , 'o' , 'u' ] # if not vowel return true if i not in vow: return True return False def reverseConsonant(s): # convert string into list s = list (s) # storing consonants in a list cons = [] for i in s: if isConsonant(i): cons.append(i) k = len (cons) - 1 # Replace the consonants with the # element present in consonant list # from last. for i in range ( len (s)): if isConsonant(s[i]): s[i] = cons[k] k - = 1 return "".join(s) print (reverseConsonant( "hello world" )) print (reverseConsonant( "bcdfghjklm" )) |
Output:
delrow ollh mlkjhgfdcb
Complexity Analysis
Time complexity: O(n)
Space Complexity: O(n) for storing consonants
Please Login to comment...