Inverting permutations in Python

前端 未结 7 1209
余生分开走
余生分开走 2021-01-12 21:08

I\'m new to programming, and I\'m trying to write a Python function to find the inverse of a permutation on {1,2,3,...,n} using the following code:

def inv(s         


        
7条回答
  •  忘掉有多难
    2021-01-12 21:29

    I believe the best way to invert a permutation perm is

    pinv = sorted(range(len(perm)), key=perm.__getitem__)
    

    This avoids repeated calls to .index() (as in the answer by SeF), which may not be very efficient (quadratic time complexity, while sorting should only take O(n log n)).

    Note, however, that this yields as a result a permutation of {0,1,...n-1}, regardless of whether the input was a permutation of {0,1,...,n-1} or of {1,2,...,n} (the latter is what is stated in the question). If the output is supposed to be a permutation of {1,2,...,n}, each element of the result has to be increased by one, for example, like this:

    pinv = [i+1 for i in sorted(range(len(perm)), key=perm.__getitem__)]
    

提交回复
热议问题