Python – Capitalize repeated characters in a string
Given an input string with lowercase letters, the task is to write a python program to identify the repeated characters in the string and capitalize them.
Examples:
Input: programming language
Output: pRoGRAMMiNG lANGuAGe
Explanation: r,m,n,a,g are repeated elementsInput: geeks for geeks
Output: GEEKS for GEEKS
Explanation: g,e,k,s are repeated elements
Approach 1:
- We have to keep the character of a string as a key and the frequency of each character of the string as a value in the dictionary.
- Traverse the string and check the frequency of each character using a dictionary if the frequency of the character is greater than one then change the character to the uppercase using the upper() function.
Implementation:
Python3
# function for changing the # repeated characters to uppercase def RepeatedUpper(s): # declaring dictionary dic = {} # Traversing the string for i in s: # If the character is already # present in dictionary then increment # the frequency of the character if i in dic: dic[i] = dic[i] + 1 # If the character is not present in # the dictionary then inserting # the character in the dictionary else : dic[i] = 1 ans = '' # traversing the string for i in s: # if the frequency of the character is # greater than one if dic[i] > 1 : # change into uppercase i = i.upper() # appending each character to the ans ans = ans + i return ans # Driver code s = 'geeks for geeks' # function call print (RepeatedUpper(s)) |
GEEKS for GEEKS
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach 2:
Using count() function.If count is greater than 1 then the character is repeated.Later on used upper() to convert to uppercase
Python3
s = "programming language" new_str = "" for i in s: if (i! = "" and s.count(i)> 1 ): new_str + = i.upper() else : new_str + = i print (new_str) |
pRoGRAMMiNG lANGuAGe
Time Complexity: O(n2) -> (count function + loop)
Auxiliary Space: O(n)
Approach 3: Using replace() and len() methods
Python3
#Capitalize repeated letters s = "programming language" length = len (s) new_str = "" for i in s: x = s.replace(i,"") if ( len (x)! = length - 1 ): new_str + = i.upper() else : new_str + = i print (new_str) |
pRoGRAMMiNG lANGuAGe
Time Complexity: O(n2) -> (replace function + loop)
Auxiliary Space: O(n)
Approach #4 : Using Counter() function
Python3
from collections import Counter s = "programming language" new_str = "" freq = Counter(s) for i in s: if (i ! = "" and freq[i] > 1 ): new_str + = i.upper() else : new_str + = i print (new_str) |
pRoGRAMMiNG lANGuAGe
Time Complexity: O(n)
Auxiliary Space: O(n)
Please Login to comment...