Suppose I have a list like this:
my_list = [A, B, C, D, E, F, G]
Actually, I use my list like a cycle. This means that after G
there is A
, and before A
, there is G
.
I want to know what is the shortest distance between, for example, B
and F
.
Obviously, the answer is 3
as F -> G -> A -> B
is shorter than B -> C -> D -> E -> F
.
What is the more "pythonic" way to compute such distance?
What I though so far is quite 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)