Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions LeetCode/medium/evalRPN_150.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import operator
from typing import List


class Solution:
def evalRPN(self, tokens: List[str]) -> int:
ops = {"+": operator.add, "-": operator.sub, "/": operator.truediv, "*": operator.mul}
stack = []

for token in tokens:
if token in ops:
num_1 = stack.pop()
num_2 = stack.pop()
operation = ops[token]
res = operation(int(num_2), int(num_1))
stack.append(res)
else:
stack.append(token)

return int(stack[0])
# NOTE: we could append token as int() then we wouldn't need to convert it before return or operation
26 changes: 26 additions & 0 deletions tests/test_leetcode_medium.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,32 @@ def test_longest_consecutive(nums, expected):
assert result == expected


@pytest.mark.parametrize(
"tokens, expected",
[
(["2", "1", "+", "3", "*"], 9),
(["4", "13", "5", "/", "+"], 6),
(
["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"],
22,
),
(["3"], 3),
(["5", "1", "2", "+", "4", "*", "+", "3", "-"], 14),
(["-2", "3", "+"], 1),
(["7", "-3", "/"], -2), # truncates toward zero
(["18", "3", "/"], 6),
(["2", "3", "*"], 6),
(["8", "2", "-"], 6),
],
)
def test_eval_rpn(tokens, expected):
from LeetCode.medium.evalRPN_150 import Solution

result = Solution().evalRPN(tokens)

assert result == expected, f"expected: {expected}, but got: {result}, input: {tokens}"


# 05: Longest Palindromic Substring
# https://leetcode.com/problems/longest-palindromic-substring/?envType=problem-list-v2&envId=hash-table

Expand Down
Loading