Open In App

Python | Record Point with Minimum difference

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with data, we might have a problem in which we need to find minimum difference between available pairs in list. This can be application to many problems in mathematics domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using min() + list comprehension 
The combination of this functions can be used to perform this task. In this, we compute the absolute difference of all pairs and then return the min of it using min().
 

Python3




# Python3 code to demonstrate working of
# Record Point with Minimum difference
# Using list comprehension + min()
 
# initialize list
test_list = [(3, 5), (1, 7), (10, 3), (1, 2)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Record Point with Minimum difference
# Using list comprehension + min()
temp = [abs(b - a) for a, b in test_list]
res = min(temp)
 
# printing result
print("Minimum difference among pairs : " + str(res))


Output : 

The original list : [(3, 5), (1, 7), (10, 3), (1, 2)]
Minimum difference among pairs : 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 min() + lambda 
This is similar to above method. In this the task performed by list comprehension is solved using lambda function, providing the difference computation logic. Returns the min. difference pair.
 

Python3




# Python3 code to demonstrate working of
# Record Point with Minimum difference
# Using lambda + min()
 
# initialize list
test_list = [(3, 5), (1, 7), (10, 3), (1, 2)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Record Point with Minimum difference
# Using lambda + min()
res = min(test_list, key = lambda sub: abs(sub[1] - sub[0]))
 
# printing result
print("Minimum difference among pairs : " + str(res))


Output : 

The original list : [(3, 5), (1, 7), (10, 3), (1, 2)]
Minimum difference among pairs : (1, 2)

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads