Add sample RPN solution
All checks were successful
Deploy to birb co. production / deploy (push) Successful in 10s
All checks were successful
Deploy to birb co. production / deploy (push) Successful in 10s
This commit is contained in:
@@ -13,9 +13,43 @@
|
|||||||
#
|
#
|
||||||
# For help, email me@bchen.dev
|
# 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:
|
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):
|
# The following test cases should pass (please copy this into your code):
|
||||||
@@ -27,6 +61,8 @@ tests = [
|
|||||||
(["50", "2", "/"], 25),
|
(["50", "2", "/"], 25),
|
||||||
(["5", "2", "/"], 2), # for division, cast to int using int(num)
|
(["5", "2", "/"], 2), # for division, cast to int using int(num)
|
||||||
(["5", "4", "3", "-", "*"], 5),
|
(["5", "4", "3", "-", "*"], 5),
|
||||||
|
(["5", "4", "6", "2", "10", "+", "*", "-", "-"], 73),
|
||||||
|
(["3", "2", "+", "5", "*"], 25)
|
||||||
]
|
]
|
||||||
for case in tests:
|
for case in tests:
|
||||||
result = rpn(case[0])
|
result = rpn(case[0])
|
||||||
|
|||||||
Reference in New Issue
Block a user