在Python中生成集合的所有排列

2021年4月21日18:47:38 发表评论 695 次浏览

排列是以特定顺序排列对象的。对象的排列顺序非常重要。一组n个元素上的排列数由n!给出。例如, 有2个! = 2 * 1 = {1, 2}的2个置换, 即{1, 2}和{2, 1}和3! = 3 * 2 * 1 = {1, 2, 3}的6个排列, 即{1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1} , {3, 1, 2}和{3, 2, 1}。

方法1(回溯)

我们可以使用这里讨论的基于回溯的递归解决方案

方法2

这个想法是一个接一个地提取所有元素, 将它们放在第一个位置, 然后递归到其余列表。

# 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 permuatation 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库中的内置置换功能来做到这一点。这是找到排列的最短技术。

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

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: