Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
So now that you have a tree, what should you do with it? Well, one
thing you’ll definitely want to do is look at it. printtree is a simple function for displaying
the tree in plain text. The output isn’t pretty, but it’s a simple way
to view small trees:
def printtree(tree,indent=''):
# Is this a leaf node?
if tree.results!=None:
print str(tree.results)
else:
# Print the criteria
print str(tree.col)+':'+str(tree.value)+'? '
# Print the branches
print indent+'T->',
printtree(tree.tb,indent+' ')
print indent+'F->',
printtree(tree.fb,indent+' ')
This is another recursive function. It takes a tree returned by
buildtree and traverses down it, and
it knows it has reached the end of a branch when it reaches the node
with results. Until it reaches that
point, it prints the criteria for the True and False branches and calls
printtree on each of them, each time
increasing the indent string.