1+ """A simple tree implementation with basic pre- and post-visitors."""
2+
3+
14class TreeNode :
2- '''A basic tree implementation.
5+ """A basic tree implementation.
6+
7+ Observe that a tree is simply a collection of connected TreeNodes.
8+
9+ Parameters
10+ ----------
11+ value:
12+ An arbitrary value associated with this node.
13+ children:
14+ The TreeNodes which are the children of this node.
15+ """
316
4- Observe that a tree is simply a collection of connected TreeNodes.'''
517 def __init__ (self , value , * children ):
6- '''
7- Parameters
8- ----------
9- value:
10- An arbitrary value associated with this node.
11- children:
12- The TreeNodes which are the children of this node.
13- '''
1418 self .value = value
1519 self .children = tuple (children )
1620
1721 def __repr__ (self ):
18- return f"{ self .__class__ .__name__ } { (self .value ,) + self .children } "
22+ """Return the canonical string representation."""
23+ return f"{ type (self ).__name__ } { (self .value ,) + self .children } "
1924
2025 def __str__ (self ):
26+ """Serialise the tree recursively as parent -> (children)."""
2127 childstring = ", " .join (map (str , self .children ))
2228 return f"{ self .value !s} -> ({ childstring } )"
2329
2430
2531def previsitor (tree , fn , fn_parent = None ):
26- ''' Traverse tree in preorder applying a function to every node.
32+ """ Traverse tree in preorder applying a function to every node.
2733
2834 Parameters
2935 ----------
@@ -33,16 +39,15 @@ def previsitor(tree, fn, fn_parent=None):
3339 A function to be applied at each node. The function should take the
3440 node to be visited as its first argument, and the result of visiting
3541 its parent as the second.
36- '''
37-
42+ """
3843 fn_out = fn (tree , fn_parent )
3944
4045 for child in tree .children :
4146 previsitor (child , fn , fn_out )
4247
4348
4449def postvisitor (expr , fn , ** kwargs ):
45- ''' Traverse an Expression in postorder applying a function to every node.
50+ """ Traverse an Expression in postorder applying a function to every node.
4651
4752 Parameters
4853 ----------
@@ -56,8 +61,7 @@ def postvisitor(expr, fn, **kwargs):
5661 arguments.
5762 **kwargs:
5863 Any additional keyword arguments to be passed to fn.
59- '''
60-
64+ """
6165 return fn (expr ,
6266 * (postvisitor (c , fn , ** kwargs ) for c in expr .operands ),
6367 ** kwargs )
0 commit comments