Leaf now extends Node, added Node representation fcuntionality.

parent decaaecb
from node import Node from node import Leaf
def generate_line(root): def generate_line(root):
""" """
Print an expression tree in a single text line. Where needed, add Print an expression tree in a single text line. Where needed, add
parentheses. parentheses.
>>> from node import Leaf >>> from node import Node, Leaf
>>> l0, l1 = Leaf(1), Leaf(2) >>> l0, l1 = Leaf(1), Leaf(2)
>>> plus = Node('+', l0, l1) >>> plus = Node('+', l0, l1)
>>> print generate_line(plus) >>> print generate_line(plus)
...@@ -51,7 +50,7 @@ def generate_line(root): ...@@ -51,7 +50,7 @@ def generate_line(root):
""" """
Get the associativity of an operator node. Get the associativity of an operator node.
""" """
if isinstance(node, Node) and len(node) > 1: if not isinstance(node, Leaf) and len(node) > 1:
op = node.title() op = node.title()
for i, group in enumerate(operators): for i, group in enumerate(operators):
...@@ -68,7 +67,7 @@ def generate_line(root): ...@@ -68,7 +67,7 @@ def generate_line(root):
""" """
s = node.title() s = node.title()
if not isinstance(node, Node): if isinstance(node, Leaf):
return s return s
arity = len(node) arity = len(node)
......
...@@ -21,20 +21,31 @@ class Node(object): ...@@ -21,20 +21,31 @@ class Node(object):
def __len__(self): def __len__(self):
return len(self.nodes) return len(self.nodes)
def __eq__(self, node):
return isinstance(node, Node) \
and self.value == node.value and self.nodes == node.nodes
#def __repr__(self):
# return repr(self.value)
def __str__(self):
return '<Node value=%s nodes=%s>' % (str(self.value), str(self.nodes))
def title(self): def title(self):
return str(self.value) return str(self.value)
class Leaf(object): class Leaf(Node):
def __init__(self, value): def __init__(self, value):
self.value = value self.value = value
self.parent = None self.parent = None
self.nodes = None
def __len__(self):
return len(str(self.value))
def __repr__(self): def __repr__(self):
return repr(self.value) return repr(self.value)
def __str__(self): def __str__(self):
return str(self.value) return str(self.value)
def title(self):
return str(self.value)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment