Can anyone help me step through the logic of the program shown below? I tried using the Python debugger. This did not help me that much though.
I do not understand the following:
preorder_traversal()
For instance at the
yield (parent, root)
line of code; does the function return these values as a generator at this point to the caller or does it return the generator and then keep going inside thepreorder_traversal()
function?Also, mind completely melts when trying to wrap my head around the recursive call to
preorder_traversal()
. Does anyone know of a way to understand this? Like a truth table or something like that that I can use to manually step through the program with a pen and paper or notepad or whatever. I think the most complicated part of this is the nesting and the recursion.
I do not understand the Node inside a Node inside a Node, etc. Or the whole adding and edge part which adds a Node to a list.
Code
class Node(object):
"""A simple digraph where each node knows about the other nodes
it leads to.
"""
def __init__(self, name):
self.name = name
self.connections = []
return
def add_edge(self, node):
"Create an edge between this node and the other."
self.connections.append(node)
return
def __iter__(self):
return iter(self.connections)
def preorder_traversal(root, seen=None, parent=None):
"""Generator function to yield the edges via a preorder traversal."""
if seen is None:
seen = set()
yield (parent, root)
if root in seen:
return
seen.add(root)
for node in root:
for (parent, subnode) in preorder_traversal(node, seen, root):
yield (parent, subnode)
return
def show_edges(root):
"Print all of the edges in the graph."
for parent, child in preorder_traversal(root):
if not parent:
continue
print '%5s -> %2s (%s)' % (parent.name, child.name, id(child))
# Set up the nodes.
root = Node('root')
a = Node('a')
b = Node('b')
c = Node('c')
# Add edges between them.
root.add_edge(a)
root.add_edge(b)
a.add_edge(b)
b.add_edge(a)
b.add_edge(c)
a.add_edge(a)
print 'ORIGINAL GRAPH:'
show_edges(root)
Thank-you for reading this.