Shao Xin
Shao Xin

Reputation: 11

Get the absolute difference between elements of a circular array

Let's say I have a array like l = [1, 3, 4, 5, 6, 8]

where the nth element represents the distance between the nth and n+1th object.

I want to find the distance between any two objects, and I used this code for this:

def dis(l_list, index1, index2, mylist):
    m = mylist.index(index1)
    n = mylist.index(index2)
    i=0
    j=0
    if n > m:
        while n >= m:
            i = i + mylist[m]
            m = m + 1
    elif n < m:
        while n <= m:
            i = i + mylist[n]
            n = n + 1
    else:
        return(0)
    j = mylist[n] % l_mylist
    print(abs(i - j))

l_mylist = input()
l_mylist = int(l_mylist)

mylist = []

mylist = list(map(int, input().split()))

i,j = input().split()
i, j=int(i), int(j)
dis(l_mylist, i, j, mylist)

but I am still getting the wrong output. Can anyone please point out where I am wrong?

Upvotes: 0

Views: 606

Answers (2)

AChampion
AChampion

Reputation: 30258

If you want to sum around a potentially circular list. You can use a collections.deque() to rotate the list, e.g.:

from collections import deque

def dist(l, i1, i2):
    d = deque(l)
    d.rotate(-i1)
    return sum(list(d)[:i2-i1]))

In []:
l = [1,2,3,4,5,6,7,8]
dist(l, 3-1, 6-1)     # 3, 4, 5

Out[]:
12

In []:
dist(l, 6-1, 3-1)     # 6, 7, 8, 1, 2

Out[]:
24

Upvotes: 1

Rohi
Rohi

Reputation: 814

def distance(first_index, second_index, my_list):
    temp_list = my_list + my_list
    if (first_index > second_index):
        first_index += len(my_list)
        requested_sum = sum(my_list[second_index-1:first_index-1])
    else:
        requested_sum = sum(my_list[first_index-1:second_index-1])
    return requested_sum

If I understood you correctly, then this should do the trick.

There are much more compact and efficient ways to do this, but this is the simplest and easiest to understand in my opinion.

Upvotes: 0

Related Questions