Inverting permutations in Python

前端 未结 7 1126
余生分开走
余生分开走 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-12 21:34

    Just since no one has recommended it here yet, I think it should be mentioned that SymPy has an entire combinatorics module, with a Permutation class:

    from sympy.combinatorics import Permutation
    o = [3, 0, 2, 1]
    p = Permutation(o)
    inv = p.__invert__()
    print(inv.array_form) # [1, 3, 2, 0]
    

    Using the SymPy class gives you access to a whole lot of other useful methods, such as comparison between equivalent permutations with ==.

    You can read the sympy.combinatorics.Permutation source code here.

    Other than that, I would recommend the answer on this page using np.arange and argsort.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题