Python program to find sum of absolute difference between all pairs in a list
Last Updated :
03 May, 2023
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))
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))
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)
Approach #4 : Using reduce()
To use the reduce function, functools module needs to be imported. The reduce function takes a function and a sequence as inputs and applies the function to the elements of the sequence in a cumulative manner.
Here is an example of how to use reduce to find the sum of absolute differences of all pairs in a list:
Python3
from functools import reduce
def sum_pairs(lst):
# Use list comprehension to compute the absolute difference between each pair of elements in the list
# and use reduce to sum the resulting list
return reduce(lambda x, y: x + y, [abs(x - y) for x in lst for y in lst if x != y]) // 2
# Test the function
lst = [9, 8, 1, 16, 15]
print(sum_pairs(lst))
#This code is contributed by Edula Vinay Kumar Reddy
Approach #5: Using nested loops and a variable to keep track of the sum of absolute differences.
- Initialize a variable, sum_abs_diff, to zero.
- Use nested loops to iterate through every pair of elements in the list.
- For each pair, compute the absolute difference between the two elements and add it to sum_abs_diff.
- Return sum_abs_diff divided by two.
Python3
def sumPairs(lst):
sum_abs_diff = 0
n = len(lst)
for i in range(n):
for j in range(i+1, n):
sum_abs_diff += abs(lst[i] - lst[j])
return sum_abs_diff
lst = [1, 2, 3, 4]
print(sumPairs(lst))
Time complexity: O(n^2)
Auxiliary space: O(1)
Approach #6: Using NumPy's broadcasting feature
NumPy provides a powerful broadcasting feature that allows performing arithmetic operations between arrays of different shapes and sizes. We can use NumPy's broadcasting feature to compute the absolute differences between all pairs of elements in a list in a vectorized way.
Here's how the algorithm works:
Convert the list to a NumPy array.
Reshape the array to have two axes.
Use broadcasting to compute the absolute differences between all pairs of elements.
Sum the resulting array and divide by 2 to account for double-counting.
Python3
import numpy as np
def sumPairs(lst):
arr = np.array(lst)
n = arr.shape[0]
# Reshape the array to have two axes
arr = arr.reshape(n, 1)
# Compute the absolute differences between all pairs of elements
diffs = np.abs(arr - arr.T)
# Sum the resulting array and divide by 2 to account for double-counting
return int(np.sum(diffs) / 2)
# Driver program
lst = [1, 2, 3, 4]
print(sumPairs(lst))
Output:
10
The np.abs() function is used to compute the absolute differences between all pairs of elements. The np.sum() function is used to sum the resulting array, and the / 2 operator is used to divide by 2 to account for double-counting.
Since the implementation uses NumPy's broadcasting feature, it is vectorized and therefore faster than the previous approaches. However, the space complexity is O(n^2), which may be an issue for large lists.
Time Complexity: O(n^2)
Space Complexity: O(n^2)
Similar Reads
Python Program to get all possible differences between set elements
Given a set, the task is to write a Python program to get all possible differences between its elements. Input : test_set = {1, 5, 2, 7, 3, 4, 10, 14} Output : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} Explanation : All possible differences are computed. Input : test_set = {1, 5, 2, 7} Output : {1
4 min read
Python Program to Find a pair with the given difference
Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Examples: Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78 Output: Pair Found: (2, 80) Input: arr[] = {90, 70, 20, 80, 50}, n = 45 Output: No Such Pair Recommended: Please solve it on "PRA
4 min read
Python Program for Maximum difference between groups of size two
Given an array of even number of elements, form groups of 2 using these array elements such that the difference between the group with highest sum and the one with lowest sum is maximum.Note: An element can be a part of one group only and it has to be a part of at least 1 group. Examples: Input : ar
3 min read
Python program to sort tuples by frequency of their absolute difference
Given a list of dual tuples, the task here is to write a Python program that can sort them by the frequency of their elements' absolute differences. Input : [(1, 6), (11, 3), (9, 1), (6, 11), (2, 10), (5, 7)] Output : [(5, 7), (1, 6), (6, 11), (11, 3), (9, 1), (2, 10)] Explanation : 7 - 5 = 2 occurs
5 min read
Difference between two Lists in Python
The difference between two lists in Python refers to the elements that are present in one list but not in the other. For example, finding the difference between lists a = [1, 2, 3, 4] and b = [3, 4, 5, 6] can result in [1, 2] by removing the common elements (3 and 4).Using setSet operations are most
3 min read
Python Program to print sum of all key value pairs in a Dictionary
Given a dictionary arr consisting of N items, where key and value are both of integer type, the task is to find the sum of all key value pairs in the dictionary. Examples: Input: arr = {1: 10, 2: 20, 3: 30}Output: 11 22 33Explanation: Sum of key and value of the first item in the dictionary = 1 + 10
5 min read
Python | Find Maximum difference between tuple pairs
Sometimes, while working with data, we might have a problem in which we need to find maximum 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 max() + list compr
5 min read
Python program to find Successive row difference in Matrix
Given a Matrix, the task is to write a Python program to perform differences from the previous row on the basis of the elements present. Input : test_list = [[5, 6, 3, 1], [7, 5, 3, 1], [3, 2], [7, 3, 3, 2], [2, 3], [9, 8, 1]] Output : [[], [7], [2], [7], [], [8, 9, 1]] Explanation : Comparing 1st a
7 min read
Python Program to remove elements that are less than K difference away in a list
Given a list, perform removal of those elements whose difference is less than K from its previous element. Input : test_list = [3, 19, 5, 8, 10, 13], K = 4Â Output : [3, 8, 13, 19]Â Explanation : 5 - 3 = 2, 2<4, hence 5 is removed, similarly, 10 - 8 is 2, less than K. Input : test_list = [15, 7, 20
3 min read
Python | Maximum absolute difference list of list
This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the maximum difference between the like indices when compared with the next list. The maximum difference between the like elements in that index is returned. Let's d
7 min read