﻿ Python: Compute the summation of the absolute difference of all distinct pairs in an given array - w3resource # Python: Compute the summation of the absolute difference of all distinct pairs in an given array

## Python Basic - 1: Exercise-26 with Solution

Write a Python program to compute the summation of the absolute difference of all distinct pairs in an given array (non-decreasing order).

Sample array: [1, 2, 3]
Then all the distinct pairs will be:
1 2
1 3
2 3

Sample Solution:

Python Code:

``````def sum_distinct_pairs(arr):
result = 0
i = 0
while i<len(arr):
result+=i*arr[i]-(len(arr)-i-1)*arr[i]
i+=1
return result
print(sum_distinct_pairs([1,2,3]))
print(sum_distinct_pairs([1,4,5]))
``````

Sample Output:

```4
8
```

Pictorial Presentation:  Flowchart: ## Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz

﻿

## Python: Tips of the Day

Checks if the given number falls within the given range.

Example:

```def tips_range(n, start, end = 0):
return start <= n <= end if end >= start else end <= n <= start
print(tips_range(2, 4, 6))
print(tips_range(4, 8))
print(tips_range(1, 3, 5))
print(tips_range(1, 3))
```

Output:

```False
True
False
True
```