3 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超7個(gè)贊
這是一個(gè)依賴于初始池中沒有重復(fù)項(xiàng)的非遞歸嘗試:
from collections import deque
def perms(pool):
agenda = deque([([], pool)])
while agenda:
perm, left = agenda.popleft()
if not left:
yield perm
# Or, to mimic the original
# print(*perm)
else:
for x in left:
agenda.append((perm+[x], [y for y in left if y != x]))
>>> list(perms('abc')))
[['a', 'b', 'c'],
['a', 'c', 'b'],
['b', 'a', 'c'],
['b', 'c', 'a'],
['c', 'a', 'b'],
['c', 'b', 'a']]

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是一種基本方法(很容易想出)。
先從簡(jiǎn)單開始。首先,讓alpha = ["a", "b", "c", "d"]. 首先找到所有以 開頭的排列"a":
start_a = [["a"]]
two_start_a = [ start_a[0] + [i] for i in alpha ]
to_three_start_a = [ [ j + [i] for i in alpha ] for j in two_start_a ]
three_start_a = []
for i in to_three_start_a:
#cleaned is to exclude list with multiple values
cleaned = [lst for lst in i if len(set(lst)) == len(lst)]
three_start_element += cleaned
to_four_start_a = [ [ j + [i] for i in alpha ] for j in three_start_a ]
four_start_a = []
for i in to_four_start_a:
#cleaned is to exclude list with multiple values
cleaned = [lst for lst in i if len(set(lst)) == len(lst)]
four_start_element += cleaned
現(xiàn)在我們four_start_a包含所有以 開頭的排列"a"。自動(dòng)版本是
start_a = [[alpha[0]]]
two_start_a = [ start_a[0] + [i] for i in alpha ]
k_start_element = two_start_element
for k in range(3, len(alpha)+1):
to_k_start_a = [ [ j + [i] for i in alpha ] for j in k_start_element ]
k_start_a = []
for i in to_k_start_a:
#cleaned is to exclude list with multiple values
cleaned = [lst for lst in i if len(set(lst)) == len(lst)]
k_start_element += cleaned
那么最后的k_start_a就是從 的第一個(gè)元素開始的所有排列alpha。
解決方案
所以,對(duì)于所有的字母,我們可以自動(dòng)化如下
all_permutations = []
for element in alpha:
start_element = [[element]]
two_start_element = [ start_element[0] + [i] for i in alpha ]
k_start_element = two_start_element
for k in range(3, len(alpha)+1):
to_k_start_element = [ [ j + [i] for i in alpha ] for j in k_start_element ]
k_start_element = []
for i in to_k_start_element:
#to exclude list with multiple values
cleaned = [lst for lst in i if len(set(lst)) == len(lst)]
k_start_element += cleaned
all_permutations.extend( k_start_element )
添加回答
舉報(bào)