Skip to content

Instantly share code, notes, and snippets.

@martijnbastiaan
Last active August 29, 2015 14:04
Show Gist options
  • Save martijnbastiaan/2563da02803673cd3b3f to your computer and use it in GitHub Desktop.
Save martijnbastiaan/2563da02803673cd3b3f to your computer and use it in GitHub Desktop.
from itertools import ifilter, imap
def merge(sets):
set_map = {}
for s in ifilter(bool, imap(set, sets)):
# Where can we store it?
try:
el = set_map[next(ifilter(lambda x: x in set_map, s))]
el |= s
except StopIteration:
el = set_map[next(iter(s))] = s
set_map.update({e: el for e in s})
return {id(s): s for s in set_map.values()}.values()
print merge([{1,2,3}, {4,5}, {3,7,8}, {8,9}, {4,10}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment