Python | Common Row elements Summation
Last Updated :
27 Apr, 2023
The problem of finding the common elements in the list of 2 lists is quite a common problem and can be dealt with with ease and also has been discussed many times. But sometimes, we require to find the elements that are in common with N lists and return their sum. Let us discuss certain ways in which this operation can be performed.
Method #1: Using reduce() + lambda + set() + sum()
This particular task can be achieved in just one line using the combination of the above functions. The reduce function can be used to operate the function “&” operation to all the list. The set function can be used to convert the list into a set to remove repetition. The task of performing sum is done using sum().
Python
# Python code to demonstrate
# Common Row elements Summation
# using reduce() + lambda + set() + sum()
# Initializing list of lists
test_list = [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
# Printing original list
print("The original list is : " + str(test_list))
# Common Row elements Summation
# using reduce() + lambda + set() + sum()
res = sum(list(reduce(lambda i, j: i & j, (set(x) for x in test_list))))
# Printing result
print("The common row elements sum is : " + str(res))
Output : The original list is : [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
The common row elements sum is : 5
Time Complexity: O(n*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 list “test_list”.
Method #2 : Using map() + intersection() + sum()
The map function can be used to convert each of the lists to set to be operated by to perform the intersection, using the set.intersection function. This is the most elegant way to perform this particular task. The task of performing sum is done using sum().
Python3
# Python3 code to demonstrate
# Common Row elements Summation
# using map() + intersection() + sum()
# Initializing list of lists
test_list = [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
# Printing original list
print ("The original list is : " + str(test_list))
# Common Row elements Summation
# using map() + intersection() + sum()
res = sum(list(set.intersection(*map(set, test_list))))
# Printing result
print ("The common row elements sum is : " + str(res))
Output : The original list is : [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
The common row elements sum is : 5
Method#3:Using a nested loop
Approach: It is to use two nested loops to compare each row with every other row, and find the common elements between them. We can use a set to keep track of the common elements, and add up their sum in the end.
Algorithm:
1. Initialize a set to store the common elements.
2. For each row in the list:
a. For each element in the row:
b. If the element is in all the rows and is not already in the set, add it to the set.
3. Calculate the sum of the elements in the set.
Python3
def common_row_elements_sum(list_):
common_elements = set()
# Enumerating list
for i, row in enumerate(list_):
for j in range(len(row)):
element = row[j]
if all(element in other_row for other_row in list_ if other_row != row) and element not in common_elements:
# Adding elements
common_elements.add(element)
# Returning sum of common elements
return sum(common_elements)
# Input list
list_ = [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
# Printing the answer
print(common_row_elements_sum(list_))
Time Complexity: O(n^3) where n is the number of rows and m is the number of elements in each row.
Auxiliary Space: O(n) for the set.
Method 4: Using itertools module:
This is a Python code that finds the common elements in the rows of a 2D list and calculates their sum. It uses the itertools module to generate all possible combinations of the rows, and then iteratively finds the intersection of the rows to get the common elements. Finally, it calculates the sum of the common elements.
- Import the itertools module.
- Generate all possible combinations of rows using the "combinations" function.
- For each combination, create a set of its elements using the built-in "set" function.
- Use the built-in "intersection" method to find the intersection of all the sets.
- Sum the elements in the resulting set.
Python3
import itertools
# input list
lst = [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
combinations = list(itertools.combinations(lst, len(lst)))
common_elements = set()
for combination in combinations:
combination_set = set(combination[0])
for row in combination[1:]:
combination_set = combination_set.intersection(row)
common_elements = common_elements.union(combination_set)
sum_common_elements = sum(common_elements)
# printing the answer
print("The common row elements sum is:", sum_common_elements)
OutputThe common row elements sum is: 5
Time complexity: O(n^3), where n is the number of rows in the list.
Space complexity: O(n), where n is the number of rows in the list.
METHOD 5:Using re method
The task is to find the sum of common elements among all the rows of a given list.
Algorithm:
- Initialize a set with the first row of the list
- Iterate through the remaining rows and update the set by taking their intersection with the set from step 1.
- Convert the set of common elements to a string with ':' separator.
- Extract all numbers from the string using regular expressions.
- Compute the sum of the numbers and print the result.
Python3
import re
# input list
lst = [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
# initialize a set to store the common elements
common_elements = set(lst[0])
# iterate over the remaining lists and
# update the common elements set
for sublist in lst[1:]:
common_elements.intersection_update(sublist)
# convert the common elements set to a
# list and join it as a string
common_elements_str = ':'.join(map(str, list(common_elements)))
# extract all numbers from the common elements string
# using regular expressions
numbers = re.findall('\d+', common_elements_str)
# compute the sum of the numbers
common_sum = sum(map(int, numbers))
# print the result
print("The common row elements sum is:", common_sum)
OutputThe common row elements sum is: 5
Time Complexity: O(N+M)
The algorithm iterates through each element of the list, and then extracts and sums the common elements using regular expressions. The time complexity of the algorithm is, therefore, O(nk + m), where n is the number of rows in the list, k is the average length of each row, and m is the total number of digits in the common elements.
Space Complexity: O((K+M)
The algorithm uses a set to store the common elements and a list to store the numbers extracted from the string. The space complexity is therefore O(k + m), where k and m are defined as before.
Similar Reads
Python | Above K elements summation
Many times we might have problem in which we need to find summation rather than the actual numbers and more often, the result is conditioned.. Letâs discuss certain ways in which this problem can be successfully solved. Method #1 : Using loop This problem can easily be solved using loop with a brute
3 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
Summation Matrix columns - Python
The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
2 min read
Python - Consecutive Row summation in Matrix
This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the sum between the like indices when compared with the next list. The sum between the like elements in that index is returned. Letâs discuss certain ways in which t
5 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 - Summation of Unique elements
This article focuses on one of the operation of getting the unique list from a list that contains a possible duplicates and performing its summation. This operations has large no. of applications and hence itâs knowledge is good to have. Method 1 : Naive method + sum() In naive method, we simply t
5 min read
Python | Alternate element summation in list
The problem of getting summation of a list is quite generic and we might some day face the issue of getting the summation of alternate elements and get the list of 2 elements containing summation of alternate elements. Let's discuss certain ways in which this can be performed. Method #1 : Using list
5 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 | Custom Index Range Summation
Development and sometimes machine learning applications require splitting lists into smaller list in a custom way, i.e on certain values on which split has to be performed and then summation. This is quite a useful utility to have knowledge about. Lets discuss certain ways in which this task can be
7 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