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
test_list = [ 'g4fg' , 'i4s5' , 'b9e4st' ]
print ( "The original list is : " + str (test_list))
res = 0
for sub in test_list:
res + = int (''.join( chr for chr in sub if chr .isdigit()))
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
test_list = [ 'g4fg' , 'i4s5' , 'b9e4st' ]
print ("The original list is : " + str (test_list))
res = sum ([ int (''.join( chr for chr in sub if chr .isdigit()))
for sub in test_list])
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
test_list = [ 'g4fg' , 'i4s5' , 'b9e4st' ]
print ( "The original list is : " + str (test_list))
res = sum ( int ("".join(re.findall(r '\d+' , sub))) for sub in test_list )
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 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
test_list = [ 'g4fg' , 'i4s5' , 'b9e4st' ]
print ( "The original list is : " + str (test_list))
la = "abcdefghijklmnopqrstuvwxyz"
ua = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
res = 0
for sub in test_list:
for j in la + ua:
sub = sub.replace(j,"")
res + = int (sub)
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)
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
test_list = [ 'g4fg' , 'i4s5' , 'b9e4st' ]
print ( "The original list is: " + str (test_list))
def extract_and_convert(s):
return int (''.join( filter ( str .isdigit, s)))
res = sum ( map (extract_and_convert, test_list))
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 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
from functools import reduce
test_list = [ 'g4fg' , 'i4s5' , 'b9e4st' ]
print ( "The original list is: " + str (test_list))
extract_and_convert = lambda s: int (''.join( filter ( str .isdigit, s)))
res = reduce ( lambda acc, x: acc + extract_and_convert(x), test_list, 0 )
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 - Random Numbers Summation
We need to do summation of random numbers. For example, n = [random.randint(1, 10) for _ in range(5)] it will generate random numbers [4, 8, 9, 4, 6] between 1 to 10 so the resultant output should be 29. Using random.randint()random.randint(a, b) function generates a random integer between a and b (
2 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 u
2 min read
Python - Retain Numbers in String
Retaining numbers in a string involves extracting only the numeric characters while ignoring non-numeric ones. Using List Comprehensionlist comprehension can efficiently iterate through each character in the string, check if it is a digit using the isdigit() method and join the digits together to fo
2 min read
Python | i^k Summation in list
Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding sum of i^k of list in just one line. Letâs discuss cer
5 min read
Python program to find all Strong Numbers in given list
Given a list, write a Python program to find all the Strong numbers in a given list of numbers. A Strong Number is a number that is equal to the sum of factorial of its digits. Examples: Input : [1, 2, 5, 145, 654, 34] Output : [1, 2, 145] Input : [15, 58, 75, 675, 145, 2] Output : [145, 2] Explanat
6 min read