python | Nested List Intersection Matrix Product
Last Updated :
17 Apr, 2023
The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists and return their product. Let’s discuss certain ways in which this operation can be performed.
Method #1 : Using reduce() + lambda + set() + loop This particular task can be achieved in just a one line using the combination of the above functions. The reduce function can be used to operate the function of “&” operation to all the list. The set function can be used to convert list into a set to remove repetition. The task of performing product is done using loop.
Python3
def prod(val) :
res = 1
for ele in val:
res * = ele
return res
test_list = [[ 2 , 3 , 5 , 8 ], [ 2 , 6 , 7 , 3 ], [ 10 , 9 , 2 , 3 ]]
print ("The original list is : " + str (test_list))
res = prod( list ( reduce ( lambda i, j: i & j, ( set (x) for x in test_list))))
print ("The common row elements product is : " + str (res))
|
Output :
The original list is : [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
The common row elements product is : 6
Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space is required
Method #2 : Using map() + intersection() + loop 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 product is done using loop.
Python3
def prod(val) :
res = 1
for ele in val:
res * = ele
return res
test_list = [[ 2 , 3 , 5 , 8 ], [ 2 , 6 , 7 , 3 ], [ 10 , 9 , 2 , 3 ]]
print ("The original list is : " + str (test_list))
res = prod( list ( set .intersection( * map ( set , test_list))))
print ("The common row elements product is : " + str (res))
|
Output :
The original list is : [[2, 3, 5, 8], [2, 6, 7, 3], [10, 9, 2, 3]]
The common row elements product is : 6
Time Complexity: O(n*n) where n is the number of elements in the test list. The loop is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(1) constant additional space needed
Share your thoughts in the comments
Please Login to comment...