def parse_g(l: List[Union[int, str]]) -> Node: top = l.pop(0) if top == "(": ans = parse_e(l) assert l.pop(0) == ")" return ans return Constant(top)
def stack_to_tree(s: List[Union[int, str]]) -> Node: top = s.pop() if type(top) is int: return Constant(top) top = cast(str, top) if top == "@": rhs = stack_to_tree(s) return UnaryOp(operations.negate, rhs) rhs = stack_to_tree(s) lhs = stack_to_tree(s) return BinOp(operations.STR_TO_BIN[top], lhs, rhs)
def queue_to_tree(q: List[Union[int, str]]) -> Node: top = q.pop(0) if type(top) is int: return Constant(top) top = cast(str, top) if top == "@": rhs = queue_to_tree(q) return UnaryOp(operations.negate, rhs) lhs = queue_to_tree(q) rhs = queue_to_tree(q) return BinOp(operations.STR_TO_BIN[top], lhs, rhs)
def test_evaluate_binop_pow(vis): op = BinOp(operations.pow, Constant(3), Constant(4)) assert vis.visit_and_get_value(op) == 81
def test_evaluate_binop_int_div(vis): op = BinOp(operations.int_div, Constant(5), Constant(2)) assert vis.visit_and_get_value(op) == 2
def test_evaluate_binop_times(vis): op = BinOp(operations.times, Constant(6), Constant(9)) assert vis.visit_and_get_value(op) == 54
def test_evaluate_binop_minus(vis): op = BinOp(operations.minus, Constant(42), Constant(51)) assert vis.visit_and_get_value(op) == -9
def test_evaluate_binop_plus(vis): op = BinOp(operations.plus, Constant(12), Constant(27)) assert vis.visit_and_get_value(op) == 39
def test_evaluate_unaryop_negate(vis): op = UnaryOp(operations.negate, Constant(-42)) assert vis.visit_and_get_value(op) == 42
def test_evaluate_unaryop_identity(vis): op = UnaryOp(operations.identity, Constant(42)) assert vis.visit_and_get_value(op) == 42
def test_evaluate_constant(vis): c = Constant(42) assert vis.visit_and_get_value(c) == 42
def test_parse_constant(): assert parse_postfix("42") == Constant(42)
def test_parse_complete_expression_tree(): assert parse_postfix("12 27 + 42 51 - *") == BinOp( operations.times, BinOp(operations.plus, Constant(12), Constant(27)), BinOp(operations.minus, Constant(42), Constant(51)), )
def test_parse_binary_operation(): assert parse_postfix("12 27 +") == BinOp(operations.plus, Constant(12), Constant(27))
def test_parse_doubly_negated_constant(): assert parse_postfix("42@@") == UnaryOp( operations.negate, UnaryOp(operations.negate, Constant(42)))
def test_parse_doubly_negated_constant(): assert parse_prefix("@@42") == UnaryOp( operations.negate, UnaryOp(operations.negate, Constant(42)))