[英]Generate unique permutations of set and subsets
I'd like to generate permutations of an iterable, including those for subsets of the iterable, without duplicates or the empty set:我想生成可迭代的排列,包括可迭代的子集的排列,没有重复或空集:
(1,2,3) --> (
(1,),
(2,),
(3,),
(1, 2),
(1, 3),
(2, 3),
(1, 2, 3),
(1, 3, 2),
(2, 1, 3),
(2, 3, 1),
(3, 1, 2),
(3, 2, 1)
)
This is essentially the powerset
function provided by more-itertools
combined with itertools.permutations
:这本质上是more-itertools
结合itertools.permutations
提供的powerset
function :
from itertools import combinations, permutations
def powerset_permutations(iterable):
"([1,2]) --> (1,) (2,) (1,2) (2,1)"
s = list(iterable)
for r in range(1, len(s)):
yield from combinations(s, r)
yield from permutations(s)
>>> list(powerset_permutations([1, 2, 3]))
[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
To include the empty set, change range(1, len(s))
to range(len(s))
:要包含空集,请将range(1, len(s))
更改为range(len(s))
:
def powerset_permutations(iterable):
"([1,2]) --> (1,) (2,) (1,2) (2,1)"
s = list(iterable)
for r in range(len(s)):
yield from combinations(s, r)
yield from permutations(s)
>>> list(powerset_permutations([1,2,3]))
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.