Skip to content

Instantly share code, notes, and snippets.

@lonnen
Created November 13, 2010 15:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lonnen/675407 to your computer and use it in GitHub Desktop.
Save lonnen/675407 to your computer and use it in GitHub Desktop.
An empty undirected graph object
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()
@lonnen
Copy link
Author

lonnen commented Dec 3, 2011

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.

@lonnen
Copy link
Author

lonnen commented Dec 8, 2011

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