Python | Embedded Numbers Summation in String List
Last Updated :
16 May, 2023
Sometimes, while working with Python lists, we can have problem in which we need to concatenate embedded numbers in Strings list and perform its summation. This can have application in domains dealing with data. Lets discuss certain ways in which this task can be performed.
Method #1 : Using join() + loop The combination of above functionalities can be used to perform this task. In this, we perform the task of extracting number using join() and loop is used to perform the task of summation.
Python3
# Python3 code to demonstrate working of
# Embedded Numbers Summation in String List
# Using join() + loop
# initializing list
test_list = ['g4fg', 'i4s5', 'b9e4st']
# printing original list
print("The original list is : " + str(test_list))
# Embedded Numbers Summation in String List
# Using join() + loop
res = 0
for sub in test_list:
res += int(''.join(chr for chr in sub if chr.isdigit()))
# printing result
print("The summation of strings : " + str(res))
Output : The original list is : ['g4fg', 'i4s5', 'b9e4st']
The summation of strings : 143
Time Complexity: O(n) where n is the total number of values in the list “test_list”.
Auxiliary Space: O(n) where n is the total number of values in the list “test_list”.
Method #2 : Using sum() + list comprehension The combination of above functions can also be used to perform this task. In this, we perform summation using sum() and list comprehension is used to compile string of numbers for summation to work upon.
Python3
# Python3 code to demonstrate working of
# Embedded Numbers Summation in String List
# Using sum() + list comprehension
# initializing list
test_list = ['g4fg', 'i4s5', 'b9e4st']
# printing original list
print("The original list is : " + str(test_list))
# Embedded Numbers Summation in String List
# Using sum() + list comprehension
res = sum([int(''.join(chr for chr in sub if chr.isdigit()))
for sub in test_list])
# printing result
print("The summation of strings : " + str(res))
Output : The original list is : ['g4fg', 'i4s5', 'b9e4st']
The summation of strings : 143
Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using the sum() + list comprehension which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method 3: Using re.findall() and sum()
Python3
import re
#initializing list
test_list = ['g4fg', 'i4s5', 'b9e4st']
# original list
print("The original list is : " + str(test_list))
#Embedded Numbers Summation in String List
#Using re.findall() and sum()
res = sum(int("".join(re.findall(r'\d+', sub))) for sub in test_list )
#printing result
print("The summation of strings : " + str(res))
OutputThe original list is : ['g4fg', 'i4s5', 'b9e4st']
The summation of strings : 143
Time complexity: O(n), where n is the total number of characters in all the strings in the list.
Auxiliary Space: O(1), as we are not using any additional data structure to store the extracted numbers.
Explanation: The re.findall() function returns a list of all the occurrences of the given pattern in the input string. In this case, the pattern is '\d+', which matches one or more digits. Then, we use a nested list comprehension to extract all the numbers and finally use the sum() function to sum them up.
Method #4 : Using replace() method and for loops
Approach
- Initiated a nested for loop
- First loop to traverse list of strings
- Second loop to replace all alphabets in string
- Finally convert numeric character to integer and sum them
- Display the sum
Python3
# Python3 code to demonstrate working of
# Embedded Numbers Summation in String List
# initializing list
test_list = ['g4fg', 'i4s5', 'b9e4st']
# printing original list
print("The original list is : " + str(test_list))
# Embedded Numbers Summation in String List
la="abcdefghijklmnopqrstuvwxyz"
ua="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
res = 0
for sub in test_list:
for j in la+ua:
sub=sub.replace(j,"")
res+=int(sub)
# printing result
print("The summation of strings : " + str(res))
OutputThe original list is : ['g4fg', 'i4s5', 'b9e4st']
The summation of strings : 143
Time Complexity : O(N*N)
Auxiliary Space : O(1)
Method #5: Using map() and sum()
- Define a function to extract digits from a string and convert them to integers.
- Use the map() function to apply the function from step 1 to each element in the list.
- Use the sum() function to calculate the summation of the resulting list of integers.
Python3
# Python3 code to demonstrate working of
# Embedded Numbers Summation in String List
# Using map() and sum()
# initializing list
test_list = ['g4fg', 'i4s5', 'b9e4st']
# printing original list
print("The original list is: " + str(test_list))
# Define a function to extract digits from a string and convert them to integers
def extract_and_convert(s):
return int(''.join(filter(str.isdigit, s)))
# Using map() and sum()
res = sum(map(extract_and_convert, test_list))
# printing result
print("The summation of strings: " + str(res))
OutputThe original list is: ['g4fg', 'i4s5', 'b9e4st']
The summation of strings: 143
Time Complexity: O(n), where n is the total number of characters in the input list.
Auxiliary Space: O(1), as we only use a constant amount of extra space for variables.
Method #6: Using reduce() and lambda
In this method, reduce() function is imported from functools module. Then, the input list test_list is initialized. A lambda function is defined to extract digits from a string and convert them to integers. Then, reduce() function is used to apply the lambda function to each element of the input list, with an initial value of 0. The reduce() function accumulates the sum of the integers extracted from each string element and returns the final result. Finally, the result is printed using the print() function.
Python3
# Python3 code to demonstrate working of
# Embedded Numbers Summation in String List
# Using reduce() and lambda
from functools import reduce
# initializing list
test_list = ['g4fg', 'i4s5', 'b9e4st']
# printing original list
print("The original list is: " + str(test_list))
# Define a lambda function to extract digits from a string and
#convert them to integers
extract_and_convert = lambda s: int(''.join(filter(str.isdigit, s)))
# Using reduce() and lambda
res = reduce(lambda acc, x: acc + extract_and_convert(x), test_list, 0)
# printing result
print("The summation of strings: " + str(res))
The original list is: ['g4fg', 'i4s5', 'b9e4st']
The summation of strings: 143
Time Complexity: O(n), where n is the number of elements in the input list, as both the lambda function and the reduce() function iterate through the list once.
Auxiliary Space: O(1), as we only use a constant amount of extra space for variables.
Similar Reads
Python - Get summation of numbers in string list Sometimes, while working with data, we can have a problem in which we receive series of lists with data in string format, which we wish to accumulate as list. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + int() This is the brute force method to perform this
3 min read
Python - Maximum Pair Summation in numeric String Sometimes, we might have a problem in which we require to get the maximum summation of 2 numbers from Strings but with a constraint of having the numbers in successions. This type of problem can occur while competitive programming. Letâs discuss certain ways in which this problem can be solved. Meth
6 min read
Python - Summation of float string list Sometimes, while working with Python list, we can have a problem in which we need to find summation in list. But sometimes, we donât have a natural number but a floating-point number in string format. This problem can occur while working with data, both in web development and Data Science domain. Le
7 min read
Insert a number in string - Python We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The num
2 min read
Python | Strings length summation Sometimes we receive data in the container that we need to process to handle it further for some essential utility. The magnitude of amount of data sometimes becomes important and needs to be known. This article discusses the total length of list of strings. Let's discuss certain ways in which this
5 min read
Python - Extract numbers from list of strings We are given a list of string we need to extract numbers from the list of string. For example we are given a list of strings s = ['apple 123', 'banana 456', 'cherry 789'] we need to extract numbers from the string in list so that output becomes [123, 456, 789].Using Regular ExpressionsThis method us
2 min read
Element indices Summation - Python Our task is to calculate the sum of elements at specific indices in a list. This means selecting elements at specific positions and computing their sum. Given a list and a set of indices, the goal is to compute the sum of elements present at those indices. For example, given the list [10, 20, 30, 40
3 min read
Python - Sort list of numbers by sum of their digits Sorting a list of numbers by the sum of their digits involves ordering the numbers based on the sum of each individual digit within the number. This approach helps prioritize numbers with smaller or larger digit sums, depending on the use case.Using sorted() with a Lambda Functionsorted() function w
2 min read
Python - Summation in Dual element Records List Sometimes, while working with Records list, we can have problem in which we perform the summation of dual tuple records and store it in list. This kind of application can occur over various domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehension T
8 min read
Python | Pair summation of list elements Sometimes, while working with Python list, one can have a problem in which one needs to find perform the summation of list in pair form. This is useful as a subproblem solution of bigger problem in web development and day-day programming. Let's discuss certain ways in which this problem can be solve
4 min read