コード例 #1
0
 def test_parse_and_evaluate(self):
     for expression, expected_value in cases:
         self.assertEqual(
             evaluate(build_parse_tree(expression)),
             expected_value
         )
コード例 #2
0
 def test_round_trip(self):
     for expression, _ in cases:
         self.assertEqual(
             construct_expression(build_parse_tree(expression)),
             expression
         )
コード例 #3
0
ファイル: traversal.py プロジェクト: PeterLD/algorithms
def print_expression(tree):
    string_value = ""

    if tree:
        string_value = "(" + print_expression(tree.get_left_child())
        string_value = string_value + str(tree.get_root_value())
        string_value = string_value + print_expression(tree.get_right_child()) + ")"

    return string_value


if __name__ == '__main__':
    expression = "( ( 10 + 5 ) * 3 )"

    print "Building parse tree for {}".format(expression)
    tree = build_parse_tree(expression)

    print "\nPreorder traversal:"
    preorder_traversal(tree)

    print "\nInorder traversal:"
    inorder_traversal(tree)

    print "\nPostorder traversal:"
    postorder_traversal(tree)

    print "\nPostorder evaluation:"
    print "Value: {}".format(postorder_evaluation(tree))

    print "\nReconstructing expression from tree:"
    print print_expression(tree)