 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Maximum difference pair in Python
Data analysis can throw a variety of challenges. In this article we will take a list with numbers as its elements. Then we will find such pairs of elements in the list which has maximum difference in value between them.
With nlargest
The approach here is to first find out all possible combinations of elements and then subtract the second element from the first. Finally apply the nlargest function form heapq module to get those pairs where the difference is maximum.
Example
from itertools import combinations from heapq import nlargest listA = [21, 14, 30, 11, 17, 18] # Given list print("Given list : ",listA) # using nlargest and combinations() res = nlargest(2, combinations(listA, 2),                key=lambda sub: abs(sub[0] - sub[1])) # print result print("Pairs with maximum difference are : ",res)  Output
Running the above code gives us the following result −
Given list : [21, 14, 30, 11, 17, 18] Pairs with maximum difference are : [(30, 11), (14, 30)]
With combinations and Max()
Here we also take the same approach as above but we get one pair as a result because we apply the max function which gives us one pair as the result.
Example
from itertools import combinations listA = [21, 14, 30, 11, 17, 18] # Given list print("Given list : ",listA) # using combinations() and lambda res = max(combinations(listA, 2), key = lambda sub: abs(sub[0]-sub[1])) # print result print("Pairs with maximum difference are : ",res)  Output
Running the above code gives us the following result −
Given list : [21, 14, 30, 11, 17, 18] Pairs with maximum difference are : (30, 11)
Advertisements
 