code_junkie

Partition a list of sets by shared elements

Nov 11th, 2011
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. [ (1,2,3), (5,2,6), (7,8,9), (6,12,13), (21,8,34), (19,20) ]
  2.  
  3. [ [ (1,2,3), (5,2,6), (6,12,13) ], [ (7,8,9), (21,8,34) ], [ (19,20) ] ]
  4.  
  5. element | set_id
  6. ----------------
  7. 1 | 1
  8. 2 | 1
  9. 3 | 1
  10. 5 | 2
  11. 2 | 2
  12. 6 | 2
  13.  
  14. nodes = [ [1,2,3], [2,4,5], [6,7,8], [10,11,12], [7,10,13], [12], [] ]
  15. links = [ set() for x in nodes ]
  16.  
  17. #first find the links
  18. for n in range(len(nodes)):
  19. for item in nodes[n]:
  20. for m in range(n+1, len(nodes)):
  21. if (item in nodes[m]):
  22. links[n].add(m)
  23. links[m].add(n)
  24.  
  25. sets = []
  26. nodes_not_in_a_set = range(len(nodes))
  27.  
  28. while len(nodes_not_in_a_set) > 0:
  29. nodes_to_explore = [nodes_not_in_a_set.pop()]
  30. current_set = set()
  31. while len(nodes_to_explore) > 0:
  32. current_node = nodes_to_explore.pop()
  33. current_set.add(current_node)
  34. if current_node in nodes_not_in_a_set:
  35. nodes_not_in_a_set.remove(current_node)
  36. for l in links[current_node]:
  37. if l not in current_set and l not in nodes_to_explore:
  38. nodes_to_explore.append(l)
  39. if len(current_set) > 0:
  40. sets.append(current_set)
  41.  
  42. for s in sets:
  43. print [nodes[n] for n in s]
  44.  
  45. [[]]
  46. [[6, 7, 8], [10, 11, 12], [7, 10, 13], [12]]
  47. [[1, 2, 3], [2, 4, 5]]
Add Comment
Please, Sign In to add comment