反转Python中的排列 [英] Inverting permutations in Python
本文介绍了反转Python中的排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是编程新手,我正在尝试编写Python函数,以使用以下代码在{1,2,3,...,n}上查找排列的逆:
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(str):
result = []
i = list(str).index(min(list(str)))
while min(list(str)) < len(list(str)) + 1:
list(str)[i : i + 1] = [len(list(str)) + 1]
result.append(i + 1)
return result
但是,当我尝试使用该函数时,inv('<mypermutation>')
返回[]
.我想念什么吗? Python是否由于某种语法原因跳过了我的while循环?我在Google和stackoverflow上搜索的主题都没有返回任何有用的信息.
However, when I try to use the function, inv('<mypermutation>')
returns []
. Am I missing something? Is Python skipping over my while loop for some syntactical reason I don't understand? None of my google and stackoverflow searches on topics I think of are returning anything helpful.
推荐答案
如果只需要逆排列,则可以使用
If you only want the inverse permutation, you can use
def inv(perm):
inverse = [0] * len(perm)
for i, p in enumerate(perm):
inverse[p] = i
return inverse
perm = [3, 0, 2, 1]
print(inv(perm))
for i in perm:
print(inv(perm)[i])
[1, 3, 2, 0]
0
1
2
3
这篇关于反转Python中的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文