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
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__)]