2017-02-17 77 views
0

我希望有n個元素[0,1,2,...]的排列列表,對於n = n1 + n2 + n3。但是這樣的排列被分成m個分區。python中的分區排列

例如,對於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), 
...] 

任何想法?

回答

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

不OK: 列表(part_permutations_iter([2,1])) 應返回 [(0,1,2),[( 1,0,2)] – user18097

+0

我不理解你的問題。 [(0,1,2),[(1,0,2)]不是有效的語法。你能澄清一下嗎? – eguaio

+0

我想我明白你現在需要什麼。 – eguaio