生成集合和子集的唯一排列

Generate unique permutations of set and subsets

我想生成可迭代对象的排列,包括可迭代对象子集的排列,没有重复项或空集:

(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)
)

这本质上是more-itertools结合itertools.permutations提供的powerset功能:

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)]

要包含空集,请将 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)]