Python | Merge Consecutive digits Strings
Last Updated :
05 May, 2023
Sometimes, while workings with data, we can have a problem in which we need to perform a merge of digits. This is a simpler problem. But it becomes complex once we need to perform merger of certain elements like numbers that are too consecutive. Let's discuss certain ways in which this task can be performed.
Method #1: Using list comprehension + groupby() + isdigit()
The combination of the above functions can be used to perform this task. In this, we first group all the digits consecutive and then perform the concatenation.
Python3
# Python3 code to demonstrate
# Merge Consecutive digits Strings
# using list comprehension + groupby() + isdigit()
from itertools import groupby
# Initializing list
test_list = ['gfg', '1', '2', 'is', '5', 'best', '6', '7']
# printing original list
print("The original list is : " + str(test_list))
# Merge Consecutive digits Strings
# using list comprehension + groupby() + isdigit()
res = [sub for i, j in groupby(test_list, str.isdigit) for sub in ([''.join(j)] if i else j)]
# printing result
print ("List after digit merge : " + str(res))
Output : The original list is : ['gfg', '1', '2', 'is', '5', 'best', '6', '7']
List after digit merge : ['gfg', '12', 'is', '5', 'best', '67']
Time Complexity: O(N) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(N), where n is the number of elements in the new res list
Method #2 : Using regex + join()
The combinations of the above functions can also be used to deal with this. In this, we find the digits using regex function and perform merger using join(). Works only with single characters.
Python3
# Python3 code to demonstrate
# Merge Consecutive digits Strings
# using regex() + join()
import re
# Initializing list
test_list = ['g', '1', '2', 'i', '5', 'b', '6', '7']
# Printing original list
print("The original list is : " + str(test_list))
# Merge Consecutive digits Strings
# using regex() + join()
res = re.findall('\d+|.', ''.join(test_list))
# Printing result
print("List after digit merge : " + str(res))
Output : The original list is : ['g', '1', '2', 'i', '5', 'b', '6', '7']
List after digit merge : ['g', '12', 'i', '5', 'b', '67']
Method 3: Using Iteration and Concatenation
Python3
# Merging consecutive digits
# using Iteration and Concatenation
def merge_consecutive_digits(lst):
res = []
temp = ''
for i in lst:
if i.isdigit():
temp += i
else:
if temp:
res.append(temp)
temp = ''
res.append(i)
if temp:
res.append(temp)
return res
# Input list
test_list = ['gfg', '1', '2', 'is', '5', 'best', '6', '7']
# Print statemens
print("The original list is :", test_list)
print("List after digit merge:", merge_consecutive_digits(test_list))
OutputThe original list is : ['gfg', '1', '2', 'is', '5', 'best', '6', '7']
List after digit merge: ['gfg', '12', 'is', '5', 'best', '67']
Time complexity: O(N), where n is the length of the input list.
Space complexity: O(N), where n is the length of the input list.
Explanation: The function merge_consecutive_digits takes a list as input and iterates through each element. If the current element is a digit, it concatenates it to a temporary string. If the current element is not a digit, it appends the temporary string to the result list, if the temporary string is not empty, and then resets the temporary string. Finally, if the temporary string is not empty, it appends it to the result list.
Method 4: Using the built-in reduce() function.
Steps:
- Initialize the input list test_list.
- Check if the test_list is not empty.
- Use the reduce() function to iterate over the elements of the test_list.
- In each iteration, check if the current element y is a digit and the last element of the accumulator list x is also a digit.
- If the above condition is true, then merge the current element y with the last element of the accumulator list x.
- If the above condition is not true, then append the current element y to the accumulator list x.
- Return the final accumulator list x after all iterations.
- If the test_list is empty, return an empty list.
Python3
# import reduce() function
from functools import reduce
# Initializing list
test_list = ['gfg', '1', '2', 'is', '5', 'best', '6', '7']
# Printing original list
print("The original list is : " + str(test_list))
# Merge Consecutive digits Strings using reduce() function
if test_list:
res = reduce(lambda x, y: x[:-1] + [x[-1] + y] if x and isinstance(
x[-1], str) and x[-1].isdigit() and y.isdigit() else x + [y], test_list, [])
else:
res = []
# Printing result
print("List after digit merge : " + str(res))
# This code contributed by tvsk
OutputThe original list is : ['gfg', '1', '2', 'is', '5', 'best', '6', '7']
List after digit merge : ['gfg', '12', 'is', '5', 'best', '67']
Time complexity: O(N), where n is the length of the input list test_list. The reduce() function iterates over all the elements of the list once.
Auxiliary space: O(N), where n is the length of the input list test_list. The accumulator list x can grow up to the size of the input list test_list.
Method 5:Using a recursive function
Steps:
- Define the function merge_consecutive_digits(lst) that takes a list lst as input.
- Check if the input list is empty. If it is, return an empty list.
- Check if the first element of the list is a digit. If it is, find the index i of the next non-digit element in the list.
- Slice the input list from index 0 up to index 'i', and join the resulting sublist into a single string.
- Recursively call the merge_consecutive_digits() function on the remainder of the input list starting from index i. Concatenate the string from step 4 with the result of the recursive call from step 5.
- If the first element of the input list is not a digit, return a list containing the first element concatenated with the result of a recursive call to merge_consecutive_digits() on the remainder of the input list starting from the index.
- Combine the results of the recursive calls in steps 5 and 7 into a single list.
- Return the final list.
Python3
def merge_consecutive_digits(lst):
if not lst:
return []
if lst[0].isdigit():
i = 1
while i < len(lst) and lst[i].isdigit():
i += 1
# Merge consecutive digits
return [''.join(lst[:i])] + merge_consecutive_digits(lst[i:])
else:
return [lst[0]] + merge_consecutive_digits(lst[1:])
# Input list
test_list = ['gfg', '1', '2', 'is', '5', 'best', '6', '7']
# printing input list
print("The original list is : " + str(test_list))
res = merge_consecutive_digits(test_list)
# Printitng list after merging
print("List after digit merge : " + str(res))
# This code is contributed by Jyothi pinjala
OutputThe original list is : ['gfg', '1', '2', 'is', '5', 'best', '6', '7']
List after digit merge : ['gfg', '12', 'is', '5', 'best', '67']
Time complexity: O(n), where n is the length of the input list. This is because each element of the list is visited exactly once during the recursive function call.
Auxiliary Space: O(n), because the function call stack can grow up to the size of the input list in the worst case when all elements are digits. In addition, the function creates new lists during concatenation and slicing, which adds to the space complexity. However, the size of these lists is proportional to the size of the input list, so the space complexity is still O(n).
Method 6: Method 6: Using a stack
- Initialize an empty stack.
- Traverse the input list from left to right.
- If the current element is a digit and the stack is not empty, and the top element of the stack is also a digit, then pop the top element of the stack and append it to the current digit.
- Otherwise, push the current element onto the stack.
- After traversing the entire input list, pop all the remaining elements from the stack and append them to the output list.
- Return the output list.
Python3
def merge_consecutive_digits(lst):
stack = []
res = []
for i in range(len(lst)):
if lst[i].isdigit() and stack and stack[-1].isdigit():
stack[-1] += lst[i]
else:
stack.append(lst[i])
while stack:
res.append(stack.pop())
return res[::-1]
# Input list
test_list = ['gfg', '1', '2', 'is', '5', 'best', '6', '7']
# Printing original list
print("The original list is : " + str(test_list))
res = merge_consecutive_digits(test_list)
# Printing list after merging
print("List after digit merge : " + str(res))
OutputThe original list is : ['gfg', '1', '2', 'is', '5', 'best', '6', '7']
List after digit merge : ['gfg', '12', 'is', '5', 'best', '67']
Time complexity: O(N), where n is the length of the input list.
Auxiliary space: O(N), where n is the length of the input list (worst case, when there are no consecutive digits).
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read