这个问题在这里已有答案:
尝试创建一个函数排列,它接受一组元素并返回其所有排列的集合,其中排列是元组类型。这是我的代码:
def permutations(s):
str1 = list(s)
if len(str1) <= 1:
print(s)
else:
for i in range(0, len(s)):
str1[0], str1[i] = str1[i], str1[0]
permutations(str1[1:])
str1[0], str1[i] = str1[i], str1[0]
给出这个输入
print(sorted(permutations({1,2,3})))
它应该回来
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
但经过很多头痛我似乎只能得到
[3][2][3][1][1][2]
您可以在标准库中使用permutations from itertools来计算所有排列
from itertools import permutations
out = list(permutations({1,2,3}))
print(out)
#Output
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
您可能正在寻找一种算法,例如递归算法。不久前我写了它(作为练习):
def get_permutations(array):
result = list()
def permute(x, index, acc=[0] * len(array)):
if index == len(array):
result.append(acc[:])
acc = list()
return None
for j in range(len(x)):
acc[index] = x[j]
_x = x[:]
_x.pop(j)
permute(_x, index + 1, acc)
permute(array, 0)
return result