How to rotate a Python list to centre a specific value

Viewed 95

I have a requirement to rotate a varying length list so that a specified value is centred in the list (i.e. rotating left or right as required).

Say I have a list:

lst = [1, 2, 3, 4, 5]

So assuming 1 is specified, then the rotated list should look like this:

lst = [4, 5, 1, 2, 3]

I know the slicing formula for rotating a list is lst = lst[n:] + lst[:n] but I'm having challenges dynamically coming up with n. I've tried using len(lst) // 2) and trying to use the list index of the specified value against that to work out n, but I can't seem to get it right.

Any suggestions? (this task is from a JetBrains Academy course that doesn't explain things well...)

2 Answers

The rotation point needs to be computed based on the index of the value and the length of the list, since you want to rotate into the middle we subtract (len(lst)-1)//2 from the index and take the modulus relative to the length to find the rotation point:

lst = [1, 2, 3, 4, 5]
l = len(lst)

for n in lst:
    i = lst.index(n)
    r = (i-(l-1)//2) % l
    out = lst[r:] + lst[:r]
    print(out)

Output:

[4, 5, 1, 2, 3]
[5, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 1]
[3, 4, 5, 1, 2]

You are on the right track with using len(lst) // 2, this will always give you the middle of the list (if it is an odd amount of entries) what I would do is use a for loop to keep rotating until the middle value is correct, this makes it easier in the case that there are multiple of the same value.

The code should look something like this:

lst=[1,2,3,4,5]
while(lst[len(lst)//2] != 1):  #while the middle value is not 1
    lst.insert(0,lst[-1])      #add the last value to the front
    lst = lst[:-1]             # remove the last value from the end
Related