Minimum distance between two elements of a circular list?

Suppose I have a list like this:

my_list = [A, B, C, D, E, F, G]

      

Actually, I am using my list as a loop. This means that G

there is after A

and A

there is before G

.

I want to know what is the shortest distance between, for example, B

and F

.

Obviously the answer 3

is because it is F -> G -> A -> B

shorter B -> C -> D -> E -> F

.

What is the more "pythonic" way to calculate this distance?

What I have so far is pretty ugly (assuming I know the index):

def distance(len_my_list, idx_1, idx_2):
    right = max(idx_1, idx_2)
    left = min(idx_1, idx_2)
    dist_1 = right - left
    dist_2 = (len_my_list - right) + left
    return min(dist_1, dist_2)

      

+3


source to share


1 answer


Since you are treating the list as circular, you can use modular arithmetic to find the two distances.

You just need to compute the first index minus the second (modulo the length of the list), and the second one minus the first (modulo the length of the list). The shortest path is at least two values.

In Python code, keeping your variable names:



def distance(len_my_list, idx_1, idx_2):
    i = (idx_1 - idx_2) % len_my_list
    j = (idx_2 - idx_1) % len_my_list
    return min(i, j)

      

In your example, it i

is equal to 3 and j

equal to 4. So the function returns 3.

+5


source







All Articles