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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With