Python - Custom Consecutive character repetition in String
Last Updated :
28 Feb, 2023
Given a String, repeat characters consecutively by number mapped in dictionary.
Input : test_str = 'Geeks4Geeks', test_dict = {"G" : 3, "e" : 1, "4" : 3, "k" : 5, "s" : 3}
Output : GGGeekkkkksss444GGGeekkkkksss
Explanation : Each letter repeated as per value in dictionary.
Input : test_str = 'Geeks4Geeks', test_dict = {"G" : 3, "e" : 1, "4" : 3, "k" : 5, "s" : 1}
Output : GGGeekkkkks444GGGeekkkkks
Explanation : Each letter repeated as per value in dictionary.
Method #1 : Using loop
This is one of the ways in which this task can be performed. In this, we iterate through each character and check in map its repetition and repeat for that amount.
Python3
# Python3 code to demonstrate working of
# Custom Consecutive character repetition in String
# Using loop
# initializing string
test_str = 'Geeks4Geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing dictionary
test_dict = {"G" : 3, "e" : 2, "4" : 4, "k" : 5, "s" : 3}
res = ""
for ele in test_str:
# using * operator for repetition
# using + for concatenation
res += ele * test_dict[ele]
# printing result
print("The filtered string : " + str(res))
OutputThe original string is : Geeks4Geeks
The filtered string : GGGeeeekkkkksss4444GGGeeeekkkkksss
Time Complexity: O(n)
Space Complexity: O(n)
Method #2 : Using list comprehension + join()
This is yet another way in which this task can be performed. In this, we perform similar task as above function. The only difference being we use join() to merge the created repetition list.
Python3
# Python3 code to demonstrate working of
# Custom Consecutive character repetition in String
# Using list comprehension + join()
# initializing string
test_str = 'Geeks4Geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing dictionary
test_dict = {"G" : 3, "e" : 2, "4" : 4, "k" : 5, "s" : 3}
# using join to perform concatenation of strings
res = "".join([ele * test_dict[ele] for ele in test_str])
# printing result
print("The filtered string : " + str(res))
OutputThe original string is : Geeks4Geeks
The filtered string : GGGeeeekkkkksss4444GGGeeeekkkkksss
Time Complexity: O(n)
Space Complexity: O(n)
Method#3: Using Recursive method.
Algorithm:
- If the input string string is empty, return an empty string.
- Else, separate the first character first_char of string from the rest of the string rest_of_string.
- Use the get() method on the repetitions dictionary to determine how many times the first_char should be repeated. If the character is not in the dictionary, default to repeating it once.
- Recursively call repeat_chars_recursively on the rest_of_string and concatenate the repeated first_char to the result.
- Return the final concatenated string.
Python3
def repeat_chars_recursively(string, repetitions):
if not string: # base case: empty string
return ''
else:
first_char = string[0]
rest_of_string = string[1:]
repeated_char = first_char * repetitions.get(first_char, 1)
return repeated_char + repeat_chars_recursively(rest_of_string, repetitions)
# initializing string
test_str = 'Geeks4Geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing dictionary
test_dict = {"G" : 3, "e" : 2, "4" : 4, "k" : 5, "s" : 3}
res = repeat_chars_recursively(test_str, test_dict)
# printing result
print("The filtered string : " + str(res))
OutputThe original string is : Geeks4Geeks
The filtered string : GGGeeeekkkkksss4444GGGeeeekkkkksss
Time Complexity:
The time complexity of this algorithm is O(n), where n is the length of the input string string. This is because we need to iterate through the entire string once to concatenate the repeated characters.
Auxiliary Space:
The auxiliary space complexity of this algorithm is O(n), where n is the length of the input string string. This is because we need to store the intermediate result (the repeated characters) for each recursive call on the call stack until we reach the base case. The maximum depth of the call stack is also proportional to the length of the input string.
Similar Reads
Python - Consecutive Repetition of Characters Sometimes, while working with character lists we can have a problem in which we need to perform consecutive repetition of characters. This can have applications in many domains. Let us discuss certain ways in which this task can be performed. Method #1: Using list comprehension This is one of the
5 min read
Python - Character repetition string combinations Given a string list and list of numbers, the task is to write a Python program to generate all possible strings by repeating each character of each string by each number in the list. Input : test_list = ["gfg", "is", "best"], rep_list = [3, 5, 2]Output : ['gggfffggg', 'iiisss', 'bbbeeesssttt', 'gggg
3 min read
Python | Split string in groups of n consecutive characters Given a string (be it either string of numbers or characters), write a Python program to split the string by every nth character. Examples: Input : str = "Geeksforgeeks", n = 3 Output : ['Gee', 'ksf', 'org', 'eek', 's'] Input : str = "1234567891234567", n = 4 Output : [1234, 5678, 9123, 4567] Method
2 min read
Python | Custom Consecutive Character Pairing Sometimes, while working with Python Strings, we can have problem in which we need to perform the pairing of consecutive strings with deliminator. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using join() + list comprehension T
4 min read
Python - Equidistant consecutive characters Strings Given a Strings List, extract all the strings, whose consecutive characters are at the common difference in ASCII order. Input : test_list = ["abcd", "egil", "mpsv", "abd"] Output : ['abcd', 'mpsv'] Explanation : In mpsv, consecutive characters are at distance 3. Input : test_list = ["abcd", "egil",
9 min read
Python Program to Split joined consecutive similar characters Given a String, our task is to write a Python program to split on the occurrence of a non-similar character. Input : test_str = 'ggggffggisssbbbeessssstt'Output : ['gggg', 'ff', 'gg', 'i', 'sss', 'bbb', 'ee', 'sssss', 'tt']Explanation : All similar consecutive characters are converted to separate st
5 min read
Replace a String character at given index in Python In Python, strings are immutable, meaning they cannot be directly modified. We need to create a new string using various methods to replace a character at a specific index. Using slicingSlicing is one of the most efficient ways to replace a character at a specific index.Pythons = "hello" idx = 1 rep
2 min read
Consecutive characters frequency - Python This problem involves identifying characters that appear consecutively and counting how many times they appear together. Here, we will explore different methods to calculate the frequency of consecutive characters in a string.Using regular expressionsWe can use the re module to efficiently count con
3 min read
Python | Consecutive element swapping in String Sometimes, while working with strings, we can have a problem in which we may require to perform swapping of consecutive elements in string. Let's discuss certain ways in which this task can be performed. Method #1 : Using join() + zip() + generator expression The combination of above functions can b
3 min read
Python - First K consecutive digits in String Given a String and number K, extract first K consecutive digits making number. Input : test_str = "geeks5geeks43best", K = 2 Output : 43 Explanation : 43 is first 2 consecutive digits. Input : test_str = "geeks5gee2ks439best", K = 3 Output : 439 Explanation : 439 is first 3 consecutive digits. Metho
5 min read