排列是以特定顺序排列对象的。对象的排列顺序非常重要。一组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(回溯)
我们可以使用此处讨论的基于回溯的递归解决方案。
方法二
这个想法是一个接一个地提取所有元素,将它们放在第一个位置,然后递归剩下的列表。
# 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)]