Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find the average of the differences between all the numbers of a Python List

I have a python list like this,

arr = [110, 60, 30, 10, 5] 

What I need to do is actually find the difference of every number with all the other numbers and then find the average of all those differences.

So, for this case, it would first find difference between 110 and then all the remaining elements, i.e. 60, 30, 10, 5 and then it will find the difference of 60 with the remaining elements, i.e. 30, 10, 5 and etc.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

After which, it will compute the Average of all these differences.

Now, this can easily be done with two For Loops but in O(n^2) time complexity and also a little bit of messy code. I was wondering if there was a faster and more efficient way of doing this same thing?

>Solution :

I’ll just give the formula first:

n = len(arr)
out = np.mean(arr * np.arange(n-1, -n, -2) )

Explanation: You want to find the mean of

a[0] - a[1], a[0] - a[2],..., a[0] - a[n-1]
             a[1] - a[2],..., a[1] - a[n-1]
                         ...

there, your

`a[0]` occurs `n-1` times with `+` sign, `0` with `-` -> `n-1` times
`a[1]` occurs `n-2` times with `+` sign, `1` with `-` -> `n-3` times
... and so on 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading