paul@439 | 1 | #!/usr/bin/env python |
paul@439 | 2 | |
paul@439 | 3 | class Branch: |
paul@439 | 4 | def __init__(self, nodes): |
paul@439 | 5 | self.nodes = nodes |
paul@439 | 6 | |
paul@439 | 7 | def visit(self, visitor): |
paul@439 | 8 | return visitor.visitBranch(self) |
paul@439 | 9 | |
paul@439 | 10 | class Leaf: |
paul@439 | 11 | def __init__(self, value): |
paul@439 | 12 | self.value = value |
paul@439 | 13 | |
paul@439 | 14 | def visit(self, visitor): |
paul@439 | 15 | return visitor.visitLeaf(self) |
paul@439 | 16 | |
paul@439 | 17 | class Visitor: |
paul@439 | 18 | def visit(self, node): |
paul@439 | 19 | return node.visit(self) |
paul@439 | 20 | |
paul@439 | 21 | # Visitor-specific functionality. |
paul@439 | 22 | |
paul@439 | 23 | def visitBranch(self, node): |
paul@439 | 24 | sum = 0 |
paul@439 | 25 | for node in node.nodes: |
paul@439 | 26 | sum += self.visit(node) |
paul@439 | 27 | return sum |
paul@439 | 28 | |
paul@439 | 29 | def visitLeaf(self, node): |
paul@439 | 30 | return node.value |
paul@439 | 31 | |
paul@439 | 32 | tree = \ |
paul@439 | 33 | Branch(( |
paul@439 | 34 | Branch(( |
paul@439 | 35 | Leaf(10), |
paul@439 | 36 | Leaf(5) |
paul@439 | 37 | )), |
paul@439 | 38 | Leaf(2) |
paul@439 | 39 | )) |
paul@439 | 40 | |
paul@439 | 41 | visitor = Visitor() |
paul@439 | 42 | result_17 = visitor.visit(tree) |
paul@439 | 43 | |
paul@439 | 44 | # vim: tabstop=4 expandtab shiftwidth=4 |