Python | Toggle characters in words having same case
Given a string, toggle the characters of those words who have all their characters in the same case.
Examples:
Input : Geeks for Geeks
Output : Geeks FOR Geeks
Explanation: The string contains three words “Geeks”, “for”, “Geeks” out of which the word “for” contains all its characters as lower cases, therefore, toggle the case of the word. Print the remaining characters as it is.
input : HELLO world
Output : hello WORLD
Simple Approach: Consider each word in the string separately. Set two flags, one to check if all the cases of the characters are the same and another to check if the characters are upper case or lower case.
if all the characters are in the same case
if all the characters are lower case
then convert into upper case
else convert into lower case
else print the same word
Below is the implementation:
Python3
def toggle(s):
word_list = s.split()
for word in word_list:
flag = 1
if word[ 0 ].islower():
r = 1
for j in word:
if j.isupper():
flag = 0
break
else :
r = 0
for j in word:
if j.islower():
flag = 0
break
if flag = = 0 : print (word, end = " " )
else :
if r = = 1 : print (word.upper(), end = " " )
else : print (word.lower(), end = " " )
s = 'Geeks for Geeks'
toggle(s)
|
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(n)
Using Library functions : We can also use direct library functions to check if individual words are lower or upper.
Python3
def toggle(s):
word_list = s.split()
for word in word_list:
if word.islower() :
print (word.upper(), end = " " )
elif word.isupper() :
print (word.lower(), end = " " )
else :
print (word, end = " " )
s = 'Geeks for Geeks'
toggle(s)
|
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(n)
Using all() and list comprehension:
Here is a new approach Using all() and list comprehension.
Python3
def toggle_words(s):
def toggle_word(word):
if all (c.isupper() for c in word):
return word.lower()
elif all (c.islower() for c in word):
return word.upper()
else :
return word
return ' ' .join(toggle_word(word) for word in s.split())
s = 'Geeks for Geeks'
print (toggle_words(s))
s = 'HELLO world'
print (toggle_words(s))
|
Output
Geeks FOR Geeks
hello WORLD
This approach defines a generator function toggle_word which yields the toggled case of a single word. The generator function is used in a list comprehension to toggle the case of each word in the input string, and the resulting list is joined with spaces to form the final output string.
The time complexity of this approach is O(n), where n is the length of the input string. The space complexity is also O(n), as the input string is split into a list of words, and the output string is constructed by joining the toggled words with spaces.
Last Updated :
09 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...