Open In App

Python – Add K between case shifts

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string, the task is to add K when a case shift happens.

Input : test_str = ‘GeeKSforGeEKs’, K = ‘*’ 
Output : G*ee*KS*for*G*e*EK*s 
Explanation : After G, lowercase character e is present, * is inserted in between. Same goes for each insertion.

Input : test_str = ‘GeeKS’, K = ‘*’ 
Output : G*ee*KS 
Explanation : Inserted at case toggles, as explained. 

Method #1 : Using loop + isupper() + islower()

In this, we iterate for each element and check at each element if next is of different case, if yes, K is added in junction.

Python3




# Python3 code to demonstrate working of
# Add K between case shifts
# Using loop + isupper() + islower()
import re
 
# initializing string
test_str = 'GeeKSforGeEKs'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = '^'
 
res = ""
for idx in range(0, len(test_str) - 1):
    # checking for case shift
    if test_str[idx].isupper() and test_str[idx + 1].islower() or test_str[idx].islower() and test_str[idx + 1].isupper():
        res = res + test_str[idx] + K
    else:
        res = res + test_str[idx]
res = res + test_str[-1]
 
# printing result
print("String after alteration : " + str(res))


Output

The original string is : GeeKSforGeEKs
String after alteration : G^ee^KS^for^G^e^EK^s

Method #2 : Using list comprehension

Another way to solve this problem, just provides shorthand to above method.

Python3




# Python3 code to demonstrate working of
# Add K between case shifts
# Using loop + isupper() + islower()
 
# initializing string
test_str = 'GeeKSforGeEKs'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = '^'
 
# join() to get result string
res = ''.join([test_str[idx] + K if (test_str[idx].isupper() and test_str[idx + 1].islower()) or
               (test_str[idx].islower() and test_str[idx + 1].isupper()) else test_str[idx] for idx in range(0, len(test_str) - 1)])
 
res += test_str[-1]
 
# printing result
print("String after alteration : " + str(res))


Output

The original string is : GeeKSforGeEKs
String after alteration : G^ee^KS^for^G^e^EK^s

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n)

Space Complexity: O(n)

Method #3 : Using re

Here’s an implementation using the re module in Python:

Algorithm for implementing Python – Add K between case shifts approach:

Initialize the input string with the given input value.
Initialize the character k with the given input value.
Compile a regular expression pattern to match a sequence of two characters where the first character is an uppercase letter and the second character is a lowercase letter, or vice versa.
Use the sub method of the pattern object to substitute the matched sequences with the same first character, followed by the character k, followed by the same second character.
Return the modified string.

Python3




import re
 
def add_k(string, k):
    pattern = re.compile(r'([A-Z][a-z]|[a-z][A-Z])')
    return pattern.sub(lambda match: match.group()[0] + k + match.group()[1], string)
 
string = "GeeKSforGeEKs"
k = "*"
result = add_k(string, k)
print(result) # Output: G*ee*KS*for*G*e*EK*s


Output

G*ee*KS*for*Ge*EK*s

Time complexity: The time complexity of the given algorithm is O(n), where n is the length of the input string. This is because we only need to traverse the input string once to apply the substitution on all the matched sequences. The time complexity of the sub method is also O(n), as it needs to match all the occurrences of the regular expression pattern in the string.

Auxiliary space: The auxiliary space complexity of the given algorithm is O(n), where n is the length of the input string. This is because we need to create a new string object to store the modified string, which has the same length as the input string. The space complexity of the compiled regular expression pattern is also constant, as it only depends on the complexity of the pattern and not on the size of the input.

Method #5: Using itertools.groupby

This method uses itertools.groupby to group consecutive characters with the same case, and then joins them together with the separator K. The resulting groups are then joined back into a string.

  1. First, the string “GeeKSforGeEKs” is initialized and stored in the variable “test_str”.
  2. The original string is printed using the “print” statement.
  3. The character “^” is stored in the variable “K”.
  4. The itertools library is imported.
  5. The “groupby” function from itertools is used to group the characters in the string into groups of consecutive uppercase or lowercase letters. The “key” argument is used to specify the function to determine the grouping criterion. In this case, it’s a lambda function that returns True if a character is uppercase, and False if it’s lowercase.
  6. The resulting groups are stored in a list comprehension that creates a new list containing the groups as sublists.
  7. Another list comprehension is used to join the characters within each group together, using the “”.join() method, and then join the resulting groups with the separator K using the “”.join() method.
  8. The resulting modified string is stored in the variable “res”.
  9. The modified string is printed using the “print” statement.

Python3




import itertools
 
# initializing string
test_str = 'GeeKSforGeEKs'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = '^'
 
# using itertools.groupby to modify string
groups = [list(g) for k, g in itertools.groupby(test_str, key=lambda c: c.isupper())]
res = K.join([''.join(group) for group in groups])
 
# printing result
print("String after alteration : " + str(res))


Output

The original string is : GeeKSforGeEKs
String after alteration : G^ee^KS^for^G^e^EK^s

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), to store the groups and the resulting modified string.



Last Updated : 24 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads