在Python中生成集合的所有置换

排列是按特定顺序排列物体。物体的排列顺序非常重要。n个元素集合上的置换数由n!给出!。例如,有两个!=2*1=2个{1,2}的置换,即{1,2}和{2,1},和3!=3*2*1=6个{1,2,3}的置换,即{1,2,3},{1,3,2},{2,1,3},{2,3,1},{3,1,2}和{3,2,1}。

null

方法1(回溯) 我们可以使用所讨论的基于回溯的递归解决方案 在这里 . 方法2 其思想是一个接一个地提取所有元素,将它们放在第一个位置,然后重复出现剩余的列表。

Python3

# Python function to print permutations of a given list
def permutation(lst):
# If lst is empty then there are no permutations
if len (lst) = = 0 :
return []
# If there is only one element in lst then, only
# one permutation is possible
if len (lst) = = 1 :
return [lst]
# Find the permutations for lst if there are
# more than 1 characters
l = [] # empty list that will store current permutation
# Iterate the input(lst) and calculate the permutation
for i in range ( len (lst)):
m = lst[i]
# Extract lst[i] or m from the list.  remLst is
# remaining list
remLst = lst[:i] + lst[i + 1 :]
# Generating all permutations where m is first
# element
for p in permutation(remLst):
l.append([m] + p)
return l
# Driver program to test above function
data = list ( '123' )
for p in permutation(data):
print (p)


输出:

['1', '2', '3']['1', '3', '2']['2', '1', '3']['2', '3', '1']['3', '1', '2']['3', '2', '1']

方法3(直接函数) 我们可以通过简单地使用itertools库中的内置置换函数来实现这一点。这是找到排列的最短方法。

Python3

from itertools import permutations
l = list (permutations( range ( 1 , 4 )))
print (l)


输出:

[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] 

本文由 阿比特·阿加瓦尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以写一篇文章,然后将文章邮寄给评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享