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 the 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.
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?
I'll just give the formula first:
n = len(arr) out = np.sum(arr * np.arange(n-1, -n, -2) ) / (n*(n-1) / 2) # 52
Explanation: You want to find the mean of
a - a, a - a,..., a - a[n-1] a - a,..., a - a[n-1] ...
`a` occurs `n-1` times with `+` sign, `0` with `-` -> `n-1` times `a` occurs `n-2` times with `+` sign, `1` with `-` -> `n-3` times ... and so on
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module