Python – Minimum Product Pair in List
Sometimes, we need to find the specific problem of getting the pair that yields the minimum product, this can be solved by sorting and getting the first and second elements of the list. But in some case, we don’t with to change the ordering of list and perform some operation in the similar list without using extra space. Let’s discuss certain ways in which this can be performed.
Note: All elements in the list are positive integer.
Method #1 : Using list comprehension + min() + combination() + lambda This particular task can be performed using the combination of above functions in which we use list comprehension to bind all the functionalities and min function to get the minimum product, combination function finds all product internally and lambda function is used to compute the product.
Python3
from itertools import combinations
test_list = [ 3 , 4 , 1 , 7 , 9 , 1 ]
print ("The original list : " + str (test_list))
res = min (combinations(test_list, 2 ), key = lambda sub: sub[ 0 ] * sub[ 1 ])
print ("The minimum product pair is : " + str (res))
|
Output :
The original list : [3, 4, 1, 7, 9, 1]
The minimum product pair is : (1, 1)
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 list comprehension + nsmallest() + combination() + lambda This method has potential of not only finding a single minimum but also k minimum product pairs if required and uses nsmallest function instead of min function to achieve this functionality.
Python3
from itertools import combinations
from heapq import nsmallest
test_list = [ 3 , 4 , 1 , 7 , 9 , 8 ]
print ("The original list : " + str (test_list))
res = nsmallest( 2 , combinations(test_list, 2 ), key = lambda sub: sub[ 0 ] * sub[ 1 ])
print ("The minimum product pair is : " + str (res))
|
Output :
The original list : [3, 4, 1, 7, 9, 8]
The minimum product pair is : [(3, 1), (4, 1)]
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”.
Last Updated :
24 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...