4

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.

2 Answers 2

6

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)
11
  • StackOverflow is not a code writing service @Jennie
    – TheEagle
    Commented Jan 30, 2021 at 17:24
  • I agree, but I needed to clean my head with this nice little exercise, and if I can help someone …It ain't that horrible (:
    – Green
    Commented Jan 30, 2021 at 17:29
  • it was mainly meant to the OP
    – TheEagle
    Commented Jan 30, 2021 at 17:31
  • I'll do anything to avoid writing my Msc theses
    – Green
    Commented Jan 30, 2021 at 17:35
  • is there a way to decrease the execution time @Green
    – Jennie
    Commented Jan 30, 2021 at 17:45
5

Using list comprehensions and avoiding intermediate variables

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

output = []
for index in range(len(arr)):
    output.append(sum(abs(index - k) if arr[k] == arr[index] else 0 for k in range(len(arr))))

print(output)

Not the answer you're looking for? Browse other questions tagged or ask your own question.