Guest User

Untitled

a guest
May 27th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.58 KB | None | 0 0
  1. from collections import deque
  2.  
  3. o = [[1,2],[3,4],[2,3],[5,4]]
  4.  
  5. def group_lists(list_of_lists):
  6. '''Combine all items in list_of_lists that share
  7. an element recursively, until no two share an item'''
  8. queue = deque( sorted(list_of_lists, key=lambda x:min(x)) )
  9. grouped = []
  10. while len(queue) >= 2:
  11. print('queue length', len(queue))
  12. s1 = set(queue.popleft())
  13. s2 = set(queue.popleft())
  14. if s1 & s2:
  15. queue.appendleft(s1 | s2)
  16. else:
  17. grouped.append(s1)
  18. queue.appendleft(s2)
  19. if queue:
  20. grouped.append(queue.pop())
  21. return grouped
  22.  
  23. group_lists(o)
Add Comment
Please, Sign In to add comment