From 9fa4b23e6b82ff312b9a2f5e408768a0d582a5ba Mon Sep 17 00:00:00 2001 From: Brendan Chen Date: Wed, 15 Apr 2026 15:57:34 -0700 Subject: [PATCH] Add sample RPN solution --- .../notes-and-examples/2026.04.08/homework.py | 40 ++++++++++++++++++- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/shared/notes-and-examples/2026.04.08/homework.py b/shared/notes-and-examples/2026.04.08/homework.py index e50c407..bf7fab6 100644 --- a/shared/notes-and-examples/2026.04.08/homework.py +++ b/shared/notes-and-examples/2026.04.08/homework.py @@ -13,9 +13,43 @@ # # For help, email me@bchen.dev -# Use this function definition: +# Sample solution below + +# Facts: +# The last element of the list must always be an operator; otherwise there is only one element + def rpn(expression: list[str]) -> int: - return 0 + operators = "+-*/" + + def eval(expression: list[str]) -> tuple[int, int]: + """ + Evaluate RPN and return an index value pointing to the first token in the expression. + """ + for i in range(len(expression) - 1, -1, -1): + token = expression[i] + + if token in operators: + right, right_token_index = eval(expression[:i]) + + # for left, we need the index of the token that comes after right + left, left_token_index = eval(expression[:right_token_index]) + + if token == "+": + return left + right, left_token_index + elif token == "-": + return left - right, left_token_index + elif token == "*": + return left * right, left_token_index + else: + return int(left / right), left_token_index + else: + # evaluate as a literal + literal = int(token) + return literal, i + + return (0, 0) + + return eval(expression)[0] # The following test cases should pass (please copy this into your code): @@ -27,6 +61,8 @@ tests = [ (["50", "2", "/"], 25), (["5", "2", "/"], 2), # for division, cast to int using int(num) (["5", "4", "3", "-", "*"], 5), + (["5", "4", "6", "2", "10", "+", "*", "-", "-"], 73), + (["3", "2", "+", "5", "*"], 25) ] for case in tests: result = rpn(case[0])