HappyUnicorn HappyUnicorn - 1 year ago 97
Python Question



Answer Source

OP requested this to be done with a comprehension, so here's a gratuitous one liner:

(Please, please please don't do it this way)

Python 3.5.2+ (default, Sep 22 2016, 12:18:14) 
[GCC 6.2.0 20160927] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import itertools
>>> import pprint
>>> foo = {("A", "B"), ("A", "G"), ("A", "H"),
...         ("B", "C"), ("B", "H"),
...         ("C", "D"),
...         ("D", "E"), ("D", "G"), ("D", "H"),
...         ("E", "F"), ("E", "G"), ("E", "H"),
...         ("F", "I"), ("F", "J"), ("F", "K"),
...         ("G", "H")}
>>> foo1 = {k:set(x[1] for x in v) for k,v in itertools.groupby(sorted(foo | {(a, b) for (b, a) in foo}), key=lambda x: x[0])}
>>> pprint.pprint(foo1)
{'A': {'H', 'B', 'G'},
 'B': {'C', 'H', 'A'},
 'C': {'D', 'B'},
 'D': {'C', 'E', 'H', 'G'},
 'E': {'D', 'H', 'F', 'G'},
 'F': {'K', 'J', 'E', 'I'},
 'G': {'D', 'E', 'H', 'A'},
 'H': {'D', 'E', 'B', 'G', 'A'},
 'I': {'F'},
 'J': {'F'},
 'K': {'F'}}