Algorithm to generate (not quite) spanning set in Python

后端 未结 3 596
南笙
南笙 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 16:49

    Adjusting one of the solution from Python: show all possible groupings of a list:

    from itertools import combinations
    
    def cut(lst, indexes):
        last = 0
        for i in indexes:
            yield lst[last:i]
            last = i
        yield lst[last:]
    
    def generate(lst, n):
        for indexes in combinations(list(range(1,len(lst))), n - 1):
            yield list(cut(lst, indexes))
    
    data = [1,2,3,4]
    
    for i in range(1, len(data)+1):  # the only difference is here
        for g in generate(data, i):
            print(g)
    
    """
    [[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]]
    """
    

提交回复
热议问题