Find Maximum difference pair in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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)
raja
Published on 26-Aug-2020 08:01:34
Advertisements