Skip to content

Instantly share code, notes, and snippets.

@UnaiM
Created March 20, 2020 16:22
Show Gist options
  • Save UnaiM/5eb82f915b1a0b36a4b5d27c86875ecd to your computer and use it in GitHub Desktop.
Save UnaiM/5eb82f915b1a0b36a4b5d27c86875ecd to your computer and use it in GitHub Desktop.
class Item(object):
def __init__(self, name):
self.name = name
self.links = []
def __repr__(self):
return self.name
a, b, c, d, e, f, g, h = (Item(x) for x in 'abcdefgh')
a.links = [c]
b.links = [e, d]
d.links = [h]
g.links = [a]
mylist = [a, b, c, d, e, f, g, h]
groups = [[x] for x in mylist]
for item in mylist:
for other in item.links:
igrp, ogrp = (next(y for y in groups if x in y) for x in (item, other))
for grp in igrp, ogrp:
try:
groups.remove(grp)
except ValueError:
pass
groups.append(igrp + ogrp)
print groups # [[f], [b, e, d, h], [g, a, c]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment