Created
March 20, 2020 16:22
-
-
Save UnaiM/5eb82f915b1a0b36a4b5d27c86875ecd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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