Algorithm to generate (not quite) spanning set in Python

后端 未结 3 609
南笙
南笙 2020-12-18 16:29

This follows on from this question:

Algorithm to generate spanning set

Given this input: [1,2,3,4]

I\'d like to generate this set of sets in python:<

3条回答
  •  忘掉有多难
    2020-12-18 17:00

    import itertools
    a = [1, 2, 3, 4]
    n = len(a)
    for num_splits in range(n):
        for splits in itertools.combinations(range(1, n), num_splits):
            splices = zip([0] + list(splits), list(splits) + [n])
            print([a[i:j] for i, j in splices])
    

    prints

    [[1, 2, 3, 4]]
    [[1], [2, 3, 4]]
    [[1, 2], [3, 4]]
    [[1, 2, 3], [4]]
    [[1], [2], [3, 4]]
    [[1], [2, 3], [4]]
    [[1, 2], [3], [4]]
    [[1], [2], [3], [4]]
    

提交回复
热议问题