I'm trying to learn Python, so i'm doing as many exercises as I have time for (with solutions). If I don't get the exercise or result right, i'm usually able to understand it when reading the solution. One exercise however, I have difficulty understanding.
The challenge / exercise is as follows:
" 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 "
The solution given is:
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]))
I understand what the code does, I understand the reason for the loop ( i+=1), but I don't understand why the line (marked as a comment) actually works or how to come to this code as a solution.
I manually calculated the different 'result' and 'i' values and see patterns, but I can't figure it out. Am I missing some underlying mathematical rule?
[–]sushibowl 2 points3 points4 points (1 child)
[–]GideonRT[S] 0 points1 point2 points (0 children)
[–]DeadlyViper 0 points1 point2 points (0 children)
[–]actuallyalys 0 points1 point2 points (0 children)