[英]Find all possible permutations and combinations of given no. of elements in a list using Python
I need to find all possible permutations and combinations of given elements without repetition of same pairs.我需要找到给定元素的所有可能排列和组合,而不需要重复相同的对。
For example例如
list = [a,b,c]
Desired output is所需的 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)]
I tried itertools
in python to get the same pairs of output but failed.我在 python 中尝试了
itertools
以获得相同的 output 对,但失败了。 Using itertools.permutations
the output was使用
itertools.permutations
output 是
[abc,acb,bac,bca,cab,cba]
Using itertools.combinations
the output was使用
itertools.combinations
output 是
[(), ('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]
which missed the pairs like (b,a)
.错过了
(b,a)
这样的对。
Using itertools.combinations_with_replacement
give repetitive elements within the pair, eg (a,a,a),(b,b,b)
, which is not acceptable.使用
itertools.combinations_with_replacement
在对中给出重复元素,例如(a,a,a),(b,b,b)
,这是不可接受的。
The desired output should not contain repetitive pair elements.所需的 output 不应包含重复的对元素。
permutations
allows you to specify the length of the list of permutations: permutations
允许您指定排列列表的长度:
If you include the null set:如果包含 null 集:
permlist = []
for i in range(len(mylist) + 1):
permlist += itertools.permutations(mylist, i)
If you excludethe null set:如果排除 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.