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

前端 未结 6 1127
我在风中等你
我在风中等你 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:26

    using itertools.combinations, set.intersection and for-else loop:

    from itertools import *
    lis=[[1, 2, 3], [3, 6, 8], [4, 9], [6, 11]]
    def func(lis):
        for i in range(1,len(lis)+1):
           for x in combinations(lis,i):
              s=set(x[0])
              for y in x[1:]:
                  if len(s & set(y)) != 0:
                      break
                  else:
                      s.update(y)    
              else:
                  yield x
    
    
    for item in func(lis):
        print item
    

    output:

    ([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])
    

提交回复
热议问题