Created
November 13, 2010 15:24
-
-
Save lonnen/675407 to your computer and use it in GitHub Desktop.
An empty undirected graph object
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 undirected_graph(dict): | |
"""An undirected graph edge list | |
In an undirected graph edges are symmetric, so vertex order doesn't matter. | |
Store lists or dictionaries to represent attributes. | |
>>> a = undirected_graph() | |
>>> a[4,5] = True | |
>>> a[5,4] | |
True | |
>>> pair = (1,8) | |
>>> a[pair] = {"weight":5,"color":"red"} | |
>>> a[8,1]['color'] | |
'red' | |
""" | |
def __getitem__(self, key, second=None): | |
return super(undirected_graph, self).__getitem__(tuple(sorted(key))) | |
def __setitem__(self, key, value): | |
super(undirected_graph, self).__setitem__(tuple(sorted(key)), value) | |
if __name__=='__main__': | |
import doctest | |
doctest.testmod() |
Simmered on it for a bit, and I like your solution better. I've changed the class to reflect it. Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The earlier implementation worked fine for me when edges were specified out of order. If you copy and pasted the code into the python repl the line spaces caused parsing problems and it would break... maybe that was what you encountered?
In any event, I've cleaned it up a bit and included tests. It's much smaller now.