Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find sum of absolute difference between all pairs in a list
In this article, we will learn how to find the sum of absolute differences between all pairs in a list. This involves calculating |a - b| for every pair of elements and summing the results.
Problem Statement
Given a list of numbers, we need to find the sum of absolute differences between all unique pairs. For example, with list [1, 3, 5], we calculate |1-3| + |1-5| + |3-5| = 2 + 4 + 2 = 8.
Method 1: Using Nested Loops
We can use two nested loops to iterate through all pairs and calculate their absolute differences ?
def sumPairs(numbers):
diffs = []
for i, x in enumerate(numbers):
for j, y in enumerate(numbers):
if i != j:
diffs.append(abs(x - y))
# Each pair is counted twice, so divide by 2
return int(sum(diffs) / 2)
# Test the function
numbers = [22, 3, 55, 43]
result = sumPairs(numbers)
print(f"Sum of absolute differences: {result}")
Sum of absolute differences: 177
Method 2: Optimized Approach
We can avoid counting pairs twice by using proper loop indices ?
def sumPairsOptimized(numbers):
total = 0
n = len(numbers)
for i in range(n):
for j in range(i + 1, n):
total += abs(numbers[i] - numbers[j])
return total
# Test the optimized function
numbers = [22, 3, 55, 43]
result = sumPairsOptimized(numbers)
print(f"Sum of absolute differences: {result}")
# Show step-by-step calculation
print("\nStep-by-step calculation:")
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
diff = abs(numbers[i] - numbers[j])
print(f"|{numbers[i]} - {numbers[j]}| = {diff}")
Sum of absolute differences: 177 Step-by-step calculation: |22 - 3| = 19 |22 - 55| = 33 |22 - 43| = 21 |3 - 55| = 52 |3 - 43| = 40 |55 - 43| = 12
Method 3: Using List Comprehension
A more concise approach using list comprehension ?
def sumPairsComprehension(numbers):
n = len(numbers)
return sum(abs(numbers[i] - numbers[j])
for i in range(n)
for j in range(i + 1, n))
# Test with different examples
test_cases = [
[1, 3, 5],
[22, 3, 55, 43],
[10, 20, 30]
]
for numbers in test_cases:
result = sumPairsComprehension(numbers)
print(f"List {numbers}: Sum = {result}")
List [1, 3, 5]: Sum = 8 List [22, 3, 55, 43]: Sum = 177 List [10, 20, 30]: Sum = 40
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Nested Loops (Basic) | O(n²) | O(n) | Learning purposes |
| Optimized Loops | O(n²) | O(1) | Memory efficiency |
| List Comprehension | O(n²) | O(1) | Concise code |
Conclusion
The optimized approach using proper loop indices is most efficient as it avoids counting pairs twice and uses constant space. For readability, list comprehension provides a clean one-liner solution.
