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 Tutorial - Learn Python Programming Language 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. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
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
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
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
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
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