fork(2) download
  1. def combine_lists(lists):
  2. # Keep a set of processed items
  3. skip = set()
  4. sets = map(set, lists)
  5.  
  6. for i, a in enumerate(sets):
  7. # If we already returned this set, skip it
  8. if i in skip:
  9. continue
  10.  
  11. for j, b in enumerate(sets[i + 1:], i + 1):
  12. # Use a set to check if there are common numbers
  13. if a & b:
  14. skip.add(j)
  15. a |= b
  16.  
  17. # yield all sets that were not added to different sets
  18. for i, a in enumerate(lists):
  19. if i not in skip:
  20. yield a
  21.  
  22. print list(combine_lists([[13, 15, 17], [1, 2, 4], [1,7,9]]))
Success #stdin #stdout 0.01s 7736KB
stdin
Standard input is empty
stdout
[[13, 15, 17], [1, 2, 4]]