2

I want to find the minimum distance between any 2 values in a list. However, I need the minimum distance considering both 'clockwise' and 'anticlockwise' movement.

For example, I have the list [0, 4, 5, 6, 3, 1]. Say I want the distance between the pair (4,1)

Moving 'clockwise' the result is obviously 4 considering the difference in index. However, If one moves 'anti-clockwise' and considers the list connected, so 0 is a neighbour to 1. The distance would be 2, which is the result I want.

How can I achieve this?

I thought about joining the lists.

[0, 4, 5, 6, 3, 1, 0, 4, 5, 6, 3, 1]

However, then there are duplicates and I'm not sure how one would choose between these.

3
  • Is the list unique to begin with? Commented Dec 13, 2021 at 15:00
  • why not just calculate both? The "reverse" direction distance is the index of 4 + length(list) - index of 1 Commented Dec 13, 2021 at 15:01
  • 1
    How can I achieve this? - Seems you have defined what you want to accomplish. Start by writing down in words discrete things you might need to do to accomplish it; then sit back, look at those things, and organize them in a logical sequence; attempt to translate each discrete step into code, sometimes it helps to make functions; run your first attempt step by step - either with pencil and paper pretending you are the interpreter or with a debugger (if you are not using an ide you should get one); assess your attempt; adjust; repeat. Commented Dec 13, 2021 at 15:07

1 Answer 1

1

There are a couple of ways to do this. One way is to note how you get reversed index to begin with. Pretend that index(1) == -1. The distance is now index(4) - index(1) = 1 + 1 = 2. -1 just means len(a) - 1 in this case. So for every pair of indices i1 and i2, you compute the two quantities max(i1, i2) - min(i1, i2), and min(i1, i2) + len(a) - max(i1, i2), and take the smaller one.

If the values in the list are not unique, you will need to find all occurrences for each one, and use something like itertools.product to find the minimum distance.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah I understand, thank you. I implemented it and it's working perfectly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.