[英]Find all possible permutations and combinations of given no. of elements in a list using Python
我需要找到給定元素的所有可能排列和組合,而不需要重復相同的對。
例如
list = [a,b,c]
所需的 output 是
[(a),(b),(c),(a,b),(a,c),(b,a),(b,c),(c,a),(c,b),(a,b,c),(a,c,b),(b,a,c),(b,c,a),(c,a,b),(c,b,a)]
我在 python 中嘗試了itertools
以獲得相同的 output 對,但失敗了。 使用itertools.permutations
output 是
[abc,acb,bac,bca,cab,cba]
使用itertools.combinations
output 是
[(), ('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]
錯過了(b,a)
這樣的對。
使用itertools.combinations_with_replacement
在對中給出重復元素,例如(a,a,a),(b,b,b)
,這是不可接受的。
所需的 output 不應包含重復的對元素。
permutations
允許您指定排列列表的長度:
如果包含 null 集:
permlist = []
for i in range(len(mylist) + 1):
permlist += itertools.permutations(mylist, i)
如果排除 null 集:
permlist = []
for i in range(len(mylist)):
permlist += itertools.permutations(mylist, i+1)
answer = set()
L = ['a', 'b', 'c']
for i in range(len(L)+1):
for c in itertools.combinations(L, i):
for p in itertools.permutations(c):
answer.add(p)
In [288]: answer
Out[288]:
{(),
('a',),
('a', 'b'),
('a', 'b', 'c'),
('a', 'c'),
('a', 'c', 'b'),
('b',),
('b', 'a'),
('b', 'a', 'c'),
('b', 'c'),
('b', 'c', 'a'),
('c',),
('c', 'a'),
('c', 'a', 'b'),
('c', 'b'),
('c', 'b', 'a')}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.