Python program to find sum of absolute difference between all pairs in a list
Given a list of distinct elements, write a Python program to find the sum of absolute differences of all pairs in the given list.
Examples:
Input : [9, 2, 14] Output : 24 Explanation: (abs(9-2) + abs(9-14) + abs(2-14)) Input : [1, 2, 3, 4] Output : 10 Explanation: (abs(1-2) + abs(1-3) + abs(1-4) + abs(2-3) + abs(2-4) + abs(3-4))
The first approach is the brute force approach, which has been previously discussed. Here, we will discuss the pythonic approaches.
Approach #1 : Using enumerate()
Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. In this method, we have a list ‘diffs’ which contains the absolute difference. We use two loops having two variables each. One to iterate through the counter and one for the list element. In every iteration, we check if the elements are similar or not. If not, find absolute difference and append it to diffs. Finally, find the sum of list. Since each pair will be counted twice, we divide the final sum by 2 and return it.
Python3
# Python3 program to find sum of # absolute differences in all pairs def sumPairs(lst): diffs = [] for i, x in enumerate (lst): for j, y in enumerate (lst): if i ! = j: diffs.append( abs (x - y)) return int ( sum (diffs) / 2 ) # Driver program lst = [ 1 , 2 , 3 , 4 ] print (sumPairs(lst)) |
10
Approach #2 : Using itertools
Python itertools consist of permutation() method. This method takes a list as an input and return an object list of tuples that contain all permutation in a list form. Here, to find absolute difference we essentially need a permutation of two elements. Since each pair will be counted twice, we divide the final sum by 2.
Python3
# Python3 program to find sum of # absolute differences in all pairs import itertools def sumPairs(lst): diffs = [ abs (e[ 1 ] - e[ 0 ]) for e in itertools.permutations(lst, 2 )] return int ( sum (diffs) / 2 ) # Driver program lst = [ 9 , 8 , 1 , 16 , 15 ] print (sumPairs(lst)) |
74
Approach #3: Using sorted array
In this method we start with sorting the array and keep track of sum of the items list and subtract working index from it once we are done with it. We are actually subtracting (i * <number of items bigger or equal to i>) from sum of the number of items bigger or equal than i in the array.
Python3
lst = [ 2 , 4 , 1 , 3 ] # first we sort the array lst = sorted (lst) summ = sum (lst) # it is a very important variable to us result = 0 for d, i in enumerate (lst): # enumerate([6, 7, 8]) = [(0, 6), (1, 7), (2, 8)] result + = summ - (i * ( len (lst) - d)) # first index of above will look like this: 10 - 1*4 = 4-1 + 3-1 + 2-1 + 1-1 summ - = i # for instance in the second i we dont want 1-2, so we get rid of it print (result) |
10