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:
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]))
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.
Previous: Write a Python program to find the digits which are absent in a given mobile number.
Next: Write a Python program to find the type of the progression (arithmetic progression/geometric progression) and the next successive member of a given three successive members of a sequence.
What is the difficulty level of this exercise?
- New Content published on w3resource :
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework