All checks were successful
Deploy to birb co. production / deploy (push) Successful in 9s
38 lines
1.1 KiB
Python
38 lines
1.1 KiB
Python
# Make a calculator using Reverse Polish Notation. Use recursion.
|
|
# The Reverse Polish syntax completely removes the need for parentheses.
|
|
#
|
|
# Syntax examples:
|
|
# "3 + 2" -> ["3", "2", "+"]
|
|
# "3 * 4 + 2" -> ["3", "4", "*", "2", "+"]
|
|
# "3 * (4 + 2)" -> ["3", "4", "2", "+", "*"]
|
|
#
|
|
# Example for how to evaluate ["3", "4", "2", "+", "*"]:
|
|
# Start with "4 2 +" -> "6"
|
|
# Then "3 6 *" -> "18"
|
|
# Start with the "innermost" expression and work backwards (this is the recursion part)
|
|
#
|
|
# For help, email me@bchen.dev
|
|
|
|
# Use this function definition:
|
|
def rpn(expression: list[str]) -> int:
|
|
return 0
|
|
|
|
|
|
# The following test cases should pass (please copy this into your code):
|
|
tests = [
|
|
(["3", "2", "+"], 5),
|
|
(["3", "4", "*"], 12),
|
|
(["3", "4", "2", "+", "*"], 18),
|
|
([], 0),
|
|
(["50", "2", "/"], 25),
|
|
(["5", "2", "/"], 2), # for division, cast to int using int(num)
|
|
(["5", "4", "3", "-", "*"], 5),
|
|
]
|
|
for case in tests:
|
|
result = rpn(case[0])
|
|
expected = case[1]
|
|
if result == expected:
|
|
print(f"PASS: expected {expected}, got {result} for {case[0]}")
|
|
else:
|
|
print(f"FAIL: expected {expected}, got {result} for {case[0]}")
|