Code:networkx

The networkx library is a great tool for quick graph operations in python put together by the wonderful folks at Los Alamos National Labs. It uses a representation based on dictionaries of dictionaries.

A dictionary of sets is simpler, so I'll show that too. For both representations, each node is a dictionary key, and the value stores the names of its child nodes. So, a graph with nodes 1,2,3 connected in a triangle would look like:

The {1, 2, 3} notation means create a set, while {1:1, 2:2, 3:3} means create a dictionary.

To test whether a node, u is parent to a node v, we can just write,

To add a node to a tree, I would need to create a new key in the dictionary -- like so:

To put in parent-child edges, I have to add members to the right set, This version of add_children makes a directed graph, since child to parent edges were not added.

Amongst other things, networkx can visualize graphs: