产生子组合,对输出列表的长度有约束

时间:2012-07-02 11:46:47

标签: python algorithm list

这个问题可能是以下两个问题的组合,但视角略有不同。

Yielding sub combinations

Yield sub combinations with limit

我根据我的要求在第一个问题中修改了代码。

def sub_combinations(segment):
    for i in range(1, len(segment)):
            for j in sub_combinations(segment[i:]):
                    yield [segment[:i]] + j 
    yield [segment]

max = 4

for p in sub_combinations([1, 2, 3, 4, 5, 6, 7]):
    if len(p) == max:
        print map(list, p)

这样输出为:

[[1], [2], [3], [4, 5, 6, 7]]
[[1], [2], [3, 4], [5, 6, 7]]
[[1], [2], [3, 4, 5], [6, 7]]
[[1], [2], [3, 4, 5, 6], [7]]
[[1], [2, 3], [4], [5, 6, 7]]
[[1], [2, 3], [4, 5], [6, 7]]
[[1], [2, 3], [4, 5, 6], [7]]
[[1], [2, 3, 4], [5], [6, 7]]
[[1], [2, 3, 4], [5, 6], [7]]
[[1], [2, 3, 4, 5], [6], [7]]
[[1, 2], [3], [4], [5, 6, 7]]
[[1, 2], [3], [4, 5], [6, 7]]
[[1, 2], [3], [4, 5, 6], [7]]
[[1, 2], [3, 4], [5], [6, 7]]
[[1, 2], [3, 4], [5, 6], [7]]
[[1, 2], [3, 4, 5], [6], [7]]
[[1, 2, 3], [4], [5], [6, 7]]
[[1, 2, 3], [4], [5, 6], [7]]
[[1, 2, 3], [4, 5], [6], [7]]
[[1, 2, 3, 4], [5], [6], [7]]

现在的问题是,这对于更大尺寸的列表需要花费太多时间。是否有更有效/ pythonic的方式来实现这一点?我怎么能在函数本身中加入参数'max'?我尝试了很多方法,但很难处理递归函数。

1 个答案:

答案 0 :(得分:4)

似乎您想要的结果可以描述为在(例如)4个非空子列表中拆分列表的所有方法。这可以通过生成所有可能的拆分位置组合来完成:

def split_sequence(seq, chunks):
    for splits in itertools.combinations(range(1, len(seq)), chunks - 1):
        left = (None,) + splits
        right = splits + (None,)
        yield [seq[l:r] for l, r in zip(left, right)]

示例输出:

>>> list(split_sequence(range(7), 4))
[[[0], [1], [2], [3, 4, 5, 6]],
 [[0], [1], [2, 3], [4, 5, 6]],
 [[0], [1], [2, 3, 4], [5, 6]],
 [[0], [1], [2, 3, 4, 5], [6]],
 [[0], [1, 2], [3], [4, 5, 6]],
 [[0], [1, 2], [3, 4], [5, 6]],
 [[0], [1, 2], [3, 4, 5], [6]],
 [[0], [1, 2, 3], [4], [5, 6]],
 [[0], [1, 2, 3], [4, 5], [6]],
 [[0], [1, 2, 3, 4], [5], [6]],
 [[0, 1], [2], [3], [4, 5, 6]],
 [[0, 1], [2], [3, 4], [5, 6]],
 [[0, 1], [2], [3, 4, 5], [6]],
 [[0, 1], [2, 3], [4], [5, 6]],
 [[0, 1], [2, 3], [4, 5], [6]],
 [[0, 1], [2, 3, 4], [5], [6]],
 [[0, 1, 2], [3], [4], [5, 6]],
 [[0, 1, 2], [3], [4, 5], [6]],
 [[0, 1, 2], [3, 4], [5], [6]],
 [[0, 1, 2, 3], [4], [5], [6]]]