def connected_tuples(pairs):
# for every element, we keep a reference to the list it belongs to
lists_by_element = {}
def make_new_list_for(x, y):
lists_by_element[x] = lists_by_element[y] = [x, y]
def add_element_to_list(lst, el):
lst.append(el)
lists_by_element[el] = lst
def merge_lists(lst1, lst2):
merged_list = lst1 + lst2
for el in merged_list:
lists_by_element[el] = merged_list
for x, y in pairs:
xList = lists_by_element.get(x)
yList = lists_by_element.get(y)
if not xList and not yList:
make_new_list_for(x, y)
if xList and not yList:
add_element_to_list(xList, y)
if yList and not xList:
add_element_to_list(yList, x)
if xList and yList and xList != yList:
merge_lists(xList, yList)
# return the unique lists present in the dictionary
return set(tuple(l) for l in lists_by_element.values())
pairs = [(1,62),
(1,192),
(1,168),
(64,449),
(263,449),
(192,289),
(128,263),
(128,345),
(3,10),
(10,11)
]
print connected_tuples(pairs)
ZGVmIGNvbm5lY3RlZF90dXBsZXMocGFpcnMpOgogICAgIyBmb3IgZXZlcnkgZWxlbWVudCwgd2Uga2VlcCBhIHJlZmVyZW5jZSB0byB0aGUgbGlzdCBpdCBiZWxvbmdzIHRvCiAgICBsaXN0c19ieV9lbGVtZW50ID0ge30KCiAgICBkZWYgbWFrZV9uZXdfbGlzdF9mb3IoeCwgeSk6CiAgICAgICAgbGlzdHNfYnlfZWxlbWVudFt4XSA9IGxpc3RzX2J5X2VsZW1lbnRbeV0gPSBbeCwgeV0KCiAgICBkZWYgYWRkX2VsZW1lbnRfdG9fbGlzdChsc3QsIGVsKToKICAgICAgICBsc3QuYXBwZW5kKGVsKQogICAgICAgIGxpc3RzX2J5X2VsZW1lbnRbZWxdID0gbHN0CgogICAgZGVmIG1lcmdlX2xpc3RzKGxzdDEsIGxzdDIpOgogICAgICAgIG1lcmdlZF9saXN0ID0gbHN0MSArIGxzdDIKICAgICAgICBmb3IgZWwgaW4gbWVyZ2VkX2xpc3Q6CiAgICAgICAgICAgIGxpc3RzX2J5X2VsZW1lbnRbZWxdID0gbWVyZ2VkX2xpc3QKCiAgICBmb3IgeCwgeSBpbiBwYWlyczoKICAgICAgICB4TGlzdCA9IGxpc3RzX2J5X2VsZW1lbnQuZ2V0KHgpCiAgICAgICAgeUxpc3QgPSBsaXN0c19ieV9lbGVtZW50LmdldCh5KQoKICAgICAgICBpZiBub3QgeExpc3QgYW5kIG5vdCB5TGlzdDoKICAgICAgICAgICAgbWFrZV9uZXdfbGlzdF9mb3IoeCwgeSkKCiAgICAgICAgaWYgeExpc3QgYW5kIG5vdCB5TGlzdDoKICAgICAgICAgICAgYWRkX2VsZW1lbnRfdG9fbGlzdCh4TGlzdCwgeSkKCiAgICAgICAgaWYgeUxpc3QgYW5kIG5vdCB4TGlzdDoKICAgICAgICAgICAgYWRkX2VsZW1lbnRfdG9fbGlzdCh5TGlzdCwgeCkgICAgICAgICAgICAKCiAgICAgICAgaWYgeExpc3QgYW5kIHlMaXN0IGFuZCB4TGlzdCAhPSB5TGlzdDoKICAgICAgICAgICAgbWVyZ2VfbGlzdHMoeExpc3QsIHlMaXN0KQoKICAgICMgcmV0dXJuIHRoZSB1bmlxdWUgbGlzdHMgcHJlc2VudCBpbiB0aGUgZGljdGlvbmFyeQogICAgcmV0dXJuIHNldCh0dXBsZShsKSBmb3IgbCBpbiBsaXN0c19ieV9lbGVtZW50LnZhbHVlcygpKQoKCnBhaXJzID0gWygxLDYyKSwKICAgICgxLDE5MiksCiAgICAoMSwxNjgpLAogICAgKDY0LDQ0OSksCiAgICAoMjYzLDQ0OSksICAgICAgCiAgICAoMTkyLDI4OSksCiAgICAoMTI4LDI2MyksCiAgICAoMTI4LDM0NSksCiAgICAoMywxMCksCiAgICAoMTAsMTEpCiAgICBdCgpwcmludCBjb25uZWN0ZWRfdHVwbGVzKHBhaXJzKQo=
set([(1, 62, 192, 168, 289), (64, 449, 263, 128, 345), (3, 10, 11)])
Warning: cannot find your CPU L2 cache size in /proc/cpuinfo