Python – Index match element Product
Last Updated :
09 Apr, 2023
Sometimes, while working with Python list we can have a problem in which we have to compare two lists for index similarity and hence can have a task of multiplication equal index pairs. Let’s discuss certain way in which this task can be performed.
Method #1 : Using loop + zip()
This task can be performed by passing the zip(), which performs task of mapping both list with each other, to the function which computes the product according to equal indices.
Python3
def prod(val) :
res = 1
for ele in list (val):
res * = ele
return res
test_list1 = [ 5 , 6 , 10 , 4 , 7 , 1 , 19 ]
test_list2 = [ 6 , 6 , 10 , 3 , 7 , 10 , 19 ]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
res = prod(x for x, y in zip (test_list1, test_list2) if x = = y)
print ( "Multiplication of Identical elements : " + str (res))
|
Output :
The original list 1 is : [5, 6, 10, 4, 7, 1, 19]
The original list 2 is : [6, 6, 10, 3, 7, 10, 19]
Multiplication of Identical elements : 7980
Time complexity: O(M^N) as the number of combinations generated is M choose N.
Auxiliary space: O(1) constant extra space is required
Method #2 : Using reduce()
Python3
import functools
test_list1 = [ 5 , 6 , 10 , 4 , 7 , 1 , 19 ]
test_list2 = [ 6 , 6 , 10 , 3 , 7 , 10 , 19 ]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
res = 1
res = functools. reduce (( lambda x, y: x * y), [x for x, y in zip (test_list1, test_list2) if x = = y])
print ( "Multiplication of Identical elements : " + str (res))
|
Output
The original list 1 is : [5, 6, 10, 4, 7, 1, 19]
The original list 2 is : [6, 6, 10, 3, 7, 10, 19]
Multiplication of Identical elements : 7980
Time complexity: o(n)
Space complexity: o(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...