Find in python combinations of mutually exclusive sets from a list's elements

前端 未结 6 1209
我在风中等你
我在风中等你 2020-12-31 17:43

In a project I am currently working on I have implemented about 80% of what I want my program to do and I am very happy with the results.

In the remaining 20% I am f

6条回答
  •  我在风中等你
    2020-12-31 18:48

    I'd use a generator:

    import itertools
    
    def comb(seq):
       for n in range(1, len(seq)):
          for c in itertools.combinations(seq, n): # all combinations of length n
             if len(set.union(*map(set, c))) == sum(len(s) for s in c): # pairwise disjoint?
                yield list(c)
    
    for c in comb([[1, 2, 3], [3, 6, 8], [4, 9], [6, 11]]):
       print c
    

    This produces:

    [[1, 2, 3]]
    [[3, 6, 8]]
    [[4, 9]]
    [[6, 11]]
    [[1, 2, 3], [4, 9]]
    [[1, 2, 3], [6, 11]]
    [[3, 6, 8], [4, 9]]
    [[4, 9], [6, 11]]
    [[1, 2, 3], [4, 9], [6, 11]]
    

    If you need to store the results in a single list:

    print list(comb([[1, 2, 3], [3, 6, 8], [4, 9], [6, 11]]))
    

提交回复
热议问题