Skip to content

Instantly share code, notes, and snippets.

@lonnen
Created November 13, 2010 15:24
Show Gist options
  • 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 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