Most pythonic way of rotating a circular list to a canonical point

wolfram.hinderer at googlemail.com wolfram.hinderer at googlemail.com
Sun Aug 2 02:07:46 CEST 2015


Am Samstag, 1. August 2015 22:34:44 UTC+2 schrieb Lukas Barth:
> Hi!
> 
> I have a list of numbers that I treat as "circular", i.e. [1,2,3] and [2,3,1] should be the same. Now I want to rotate these to a well defined status, so that I can can compare them.
> 
> If all elements are unique, the solution is easy: find the minimum element, find its index, then use mylist[:index] + mylist[index:], i.e. the minimum element will always be at the beginning.
> 
> But say I have [0,1,0,2,0,3]. I can in fact guarantee that no *pair* will appear twice in that list, i.e. I could search for the minimum, if that is unique go on as above, otherwise find *all* positions of the minimum, see which is followed by the smallest element, and then rotate that position to the front.
> 
> Now that seems an awful lot of code for a (seemingly?) simple problem. Is there a nice, pythonic way to do this?

It's not that much code (unless I misunderstood your question):

def f(A):
    i = min(range(len(A)-1), key=lambda i: A[i:i+2])
    if [A[-1], A[0]] < A[i:i+2]:
        i = len(A) - 1
    return A[i:] + A[:i]

Examples:

f([0,2,0,1,0,3,0])
Out[23]: [0, 0, 2, 0, 1, 0, 3]

f([2,3,4,0,1])
Out[24]: [0, 1, 2, 3, 4]


Wolfram


More information about the Python-list mailing list