Add a third visitor to prove the point again. CountVisitor returns how many nodes the tree contains.
where the child counts come from node.left.accept(self) and node.right.accept(self). Three operations now share the same nodes, each living entirely in its own visitor.
class Num:
def __init__(self, value):
self.value = value
def accept(self, visitor):
return visitor.visit_num(self)
class Add:
def __init__(self, left, right):
self.left = left
self.right = right
def accept(self, visitor):
return visitor.visit_add(self)
class Mul:
def __init__(self, left, right):
self.left = left
self.right = right
def accept(self, visitor):
return visitor.visit_mul(self)
class EvalVisitor:
def visit_num(self, node):
return node.value
def visit_add(self, node):
return node.left.accept(self) + node.right.accept(self)
def visit_mul(self, node):
return node.left.accept(self) * node.right.accept(self)
class PrintVisitor:
def visit_num(self, node):
return str(node.value)
def visit_add(self, node):
return "(" + node.left.accept(self) + " + " + node.right.accept(self) + ")"
def visit_mul(self, node):
return "(" + node.left.accept(self) + " * " + node.right.accept(self) + ")"
class CountVisitor:
def visit_num(self, node):
"""Return the node count for a Num node (a leaf counts as 1)."""
# TODO: return 1
pass
def visit_add(self, node):
"""Return 1 plus the node counts of both children."""
# TODO: return 1 + node.left.accept(self) + node.right.accept(self)
pass
def visit_mul(self, node):
"""Return 1 plus the node counts of both children."""
# TODO: return 1 + node.left.accept(self) + node.right.accept(self)
passThe editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Add a third visitor to prove the point again. CountVisitor returns how many nodes the tree contains.
where the child counts come from node.left.accept(self) and node.right.accept(self). Three operations now share the same nodes, each living entirely in its own visitor.
Press Run Tests or ββ© to check your solution.