Python | Minimum key equal pairs
Last Updated :
09 Apr, 2023
Sometimes, while working with Python, we can have a problem in which we need to get all the records. This data can have similar values and we need to find minimum key’ed value pair. This kind of problem can occur while working with data. Let’s discuss certain ways in which this task can be done.
Method #1 : Using min() + groupby() + itemgetter() + list comprehension The combination of above functions can be used to perform this particular task. In this, we first group the like valued elements using groupby() and itemgetter(), and then extract the minimum of those using min() and cumulate the result in list using list comprehension.
Python3
from operator import itemgetter
from itertools import groupby
test_list = [( 4 , 3 ), ( 2 , 3 ), ( 3 , 10 ), ( 5 , 10 ), ( 5 , 6 )]
print ("The original list : " + str (test_list))
res = [ min (values) for key, values in groupby(test_list, key = itemgetter( 1 ))]
print ("Minimum key equal pairs : " + str (res))
|
Output :
The original list : [(4, 3), (2, 3), (3, 10), (5, 10), (5, 6)]
Minimum key equal pairs : [(2, 3), (3, 10), (5, 6)]
Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using the min() + groupby() + itemgetter() + list comprehension which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2 : Using setdefault() + items() + loop + list comprehension The combination of above functions can also achieve this task. In this, we convert the list tuple key-value pairs into a dictionary and assign a default value using setdefault(). The final result is computed using list comprehension.
Python3
test_list = [( 4 , 3 ), ( 2 , 3 ), ( 3 , 10 ), ( 5 , 10 ), ( 5 , 6 )]
print ("The original list : " + str (test_list))
temp = {}
for val, key in test_list:
if val < temp.setdefault(key, val):
temp[key] = val
res = [(val, key) for key, val in temp.items()]
print ("Minimum key equal pairs : " + str (res))
|
Output :
The original list : [(4, 3), (2, 3), (3, 10), (5, 10), (5, 6)]
Minimum key equal pairs : [(2, 3), (3, 10), (5, 6)]
Time Complexity: O(n*n) where n is the number of elements in the string list. The setdefault() + items() + loop + list comprehension is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res test_list.
Share your thoughts in the comments
Please Login to comment...