Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find distance metrics in python

Tags:

python

This is the array.

arr=[1,2,2,1,5,1]

i need to calculate the abs value of index differences between in and all the other elements if the same value, like explained below.

distance metric for a[0] = |0-3|+|0-5|=8
distance metric for a[1] = |1-2|=1
distance metric for a[2] = |2-1|=1
distance metric for a[3] = |3-0|+|3-5|=5
distance metric for a[4] = 0
distance metric for a[5] = |5-0|+|5-3|=7

output is

[8,1,1,5,0,7]

can someone help in coding this in python.

like image 697
Jennie Avatar asked Dec 17 '22 11:12

Jennie


1 Answers

You can use this working example:

arr=[1,2,2,1,5,1]
res = []
for i, n in enumerate(arr):
    val = 0
    occur = [j for j, x in enumerate(arr) if x == n and j != i]
    for o in occur:
        val += abs(i-o)
    res.append(val)
print(res)

[8, 1, 1, 5, 0, 7]

a bit more efficient version with a complexity of O(n**2)

arr=[1,2,2,1,5,1]
res = []
for i, n in enumerate(arr):
    val = 0
    for j, x in enumerate(arr):
        if x == n and j != i:
            val += abs(i-j)
    res.append(val)
print(res)
like image 73
Green Avatar answered Dec 30 '22 21:12

Green