Open In App

Python | Common Row elements Summation

Last Updated : 27 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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_))


Output

5

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.

  1. Import the itertools module.
  2. Generate all possible combinations of rows using the “combinations” function.
  3. For each combination, create a set of its elements using the built-in “set” function.
  4. Use the built-in “intersection” method to find the intersection of all the sets.
  5. 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)


Output

The 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:

  1. Initialize a set with the first row of the list
  2. Iterate through the remaining rows and update the set by taking their intersection with the set from step 1.
  3. Convert the set of common elements to a string with ‘:’ separator.
  4. Extract all numbers from the string using regular expressions.
  5. 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)


Output

The 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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads