
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python program to find sum of absolute difference between all pairs in a list
In this article, we will learn about the solution and approach to solve the given problem statement.
Problem statement
Given a list input , we need to find the sum of absolute difference between all pairs in a list.
Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object type.
In this method, we have a list ‘diffs’ which contains the absolute difference.
We use two loops having two variables initialized . One is to iterate through the counter and another for the list element. In every iteration, we check whether the elements are similar or not.
If not, find the absolute difference and append it to diffs list .
Finally,we find the sum of list. Since each pair will be counted twice, we divide the final sum by 2 to get the desired value and return it.
Example
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 = [22,3,55,43] print(sumPairs(lst))
Output
177
All the variables & functions are declared in the global scope and are shown below.
Conclusion
In this article, we learnt about the approach to find the absolute difference between all pairs in a list
- Related Articles
- Program to find minimum absolute sum difference in Python
- Program to find sum of concatenated pairs of all each element in a list in Python?\n
- Program to find two pairs of numbers where difference between sum of these pairs are minimized in python
- Program to find XOR sum of all pairs bitwise AND in Python
- Program to find the sum of the absolute differences of every pair in a sorted list in Python
- Program to find sum of absolute differences in a sorted array in Python
- Program to find maximum absolute sum of any subarray in Python
- Program to Find K-Largest Sum Pairs in Python
- Program to find max number of K-sum pairs in Python
- Program to find sum of widths of all subsequences of list of numbers in Python
- Python program to find Cumulative sum of a list
- Program to find kpr sum for all queries for a given list of numbers in Python
- Python program to find sum of elements in list
- Find all distinct pairs with difference equal to k in Python
- Find Maximum difference between tuple pairs in Python
