Inverting permutations in Python

前端 未结 7 1119
余生分开走
余生分开走 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:46

    A "functional style" version:

    def invert_permutation(permutation):
        return [i for i, j in sorted(enumerate(permutation), key=lambda (_, j): j)]
    

    Basically, sorting the indices i of the permutation by their values j in the permutation yields the desired inverse.

    p = [2, 1, 5, 0, 4, 3]
    
    invert_permutation(p)
    # [3, 1, 0, 5, 4, 2]
    
    # inverse of inverse = identity
    invert_permutation(invert_permutation(p)) == p
    # True
    

提交回复
热议问题