Created
August 7, 2023 19:26
-
-
Save jm96441n/2a9edd475d16091d23880ea5781e37a5 to your computer and use it in GitHub Desktop.
RPN calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
from dataclasses import dataclass | |
from typing import Any, List, Optional # noqa | |
import ipdb # type: ignore | |
class Solution: | |
functions = { | |
"+": (lambda x, y: x + y), | |
"-": (lambda x, y: x - y), | |
"*": (lambda x, y: x * y), | |
"/": (lambda x, y: math.ceil(x / y) if (x > 0 and y < 0) or (x < 0 and y > 0) else math.floor(x / y)), | |
} | |
def evalRPN(self, tokens: List[str]) -> int: | |
stack: List[int] = [int(tokens[0])] | |
for t in tokens[1:]: | |
fn = self.functions.get(t, None) | |
if fn is None: | |
stack.append(int(t)) | |
else: | |
v1 = stack.pop() | |
v2 = stack.pop() | |
stack.append(fn(v2, v1)) | |
return stack.pop() | |
@dataclass | |
class TestCase: | |
input: list[str] | |
expected_output: int | |
def main(): | |
testCases = [ | |
TestCase(input=["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"], expected_output=22), | |
TestCase(input=["4", "13", "5", "/", "+"], expected_output=6), | |
TestCase(input=["2", "1", "+", "3", "*"], expected_output=9), | |
TestCase(input=["18"], expected_output=18), | |
] | |
s = Solution() | |
for tc in testCases: | |
actual = s.evalRPN(tc.input) | |
assert actual == tc.expected_output, f"\nExpected\n\t{tc.expected_output}\nGot\n\t{actual}\nFrom\n\t{tc.input}" | |
print("All passed!") | |
""" | |
Constraints: | |
Ideas: | |
Test Cases: | |
["10","6","9","3","+","-11","*","/","*","17","+","5","+"] | |
stack = [17, 5] | |
cur = 17 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment