python中的分区排列

时间:2017-02-17 11:12:09

标签: python permutation itertools

我希望有一个n个元素[0,1,2,...]的排列列表,对于n = n1 + n2 + n3。但是这样的排列被划分为m个分区。

例如对于n1,n2 = 3,2我会:

0,1,2 | 3,4
0,1,2 | 4,3
0,2,1 | 3,4
0,2,1 | 4,3
...
2,1,0 | 4,3

如果我使用itertools:

product(permutations([0,1,2]),permutations([3,4]))

我明白了:

[((0, 1, 2), (3, 4)), ((0, 1, 2), (4, 3)), ((0, 2, 1), (3, 4)), ((0, 2, 1), (4, 3)), ((1, 0, 2), (3, 4)), ((1, 0, 2), (4, 3)), ((1, 2, 0), (3, 4)), ((1, 2, 0), (4, 3)), ((2, 0, 1), (3, 4)), ((2, 0, 1), (4, 3)), ((2, 1, 0), (3, 4)), ((2, 1, 0), (4, 3))]

但我想:

[(0, 1, 2, 3, 4), (0, 1, 2, 4, 3), ...]

如果输入可能只是分区的长度,那就太棒了:

input = [3,2]
or
input = [4,3,2]

在后一种情况下,我会得到:

[(0,1,2,3,  4,5,6,  7,8),
 (0,1,2,3,  4,5,6,  8,7),
 (0,1,2,3,  4,6,5,  7,8),
 ...]

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

根据我的理解,以下代码可以满足您的需求。

from itertools import permutations, product


def part_perm_iter(ns):
    inds = [int(sum(ns[:i])) for i in xrange(len(ns)+1)]
    pair_inds = zip(inds,inds[1:])

    for p in product( *[permutations(xrange(a,b)) for a, b in pair_inds ] ):
        yield sum(p,())

例如,print list(part_perm_iter([2,2]))将打印:

[(0, 1, 2, 3), (0, 1, 3, 2), (1, 0, 2, 3), (1, 0, 3, 2)]