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
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod

class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
operators = ['+', '-', '*', '/']

for token in tokens:
if token in operators:
# Pop two operands (note: order matters for - and /)
b = stack.pop()
a = stack.pop()

# Apply operation
if token == '+':
result = a + b
elif token == '-':
result = a - b
elif token == '*':
result = a * b
else: # token == '/'
# Truncate toward zero
result = int(a / b)

stack.append(result)
else:
# It's a number, push to stack
stack.append(int(token))

# Final result is the only element left in stack
return stack[0]
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
function evalRPN(tokens: string[]): number {
const stack: number[] = [];
const operators: string[] = ['+', '-', '*', '/'];

for (const token of tokens) {
if (operators.includes(token)) {
// Pop two operands (note: order matters for - and /)
const b = stack.pop()!;
const a = stack.pop()!;

// Apply operation
let result: number;
if (token === '+') {
result = a + b;
} else if (token === '-') {
result = a - b;
} else if (token === '*') {
result = a * b;
} else { // token === '/'
// Truncate toward zero
result = Math.trunc(a / b);
}

stack.push(result);
} else {
// It's a number, push to stack
stack.push(parseInt(token));
}
}

// Final result is the only element left in stack
return stack[0];
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import unittest
from src.my_project.interviews.top_150_questions_round_22\
.ex_53_evaluate_reverse_polish_notation import Solution

class EvaluateReversePolishNotationTestCase(unittest.TestCase):

def test_first_pattern(self):
solution = Solution()
output = solution.evalRPN(tokens = ["2","1","+","3","*"])
target = 9
self.assertEqual(output, target)

def test_second_pattern(self):
solution = Solution()
output = solution.evalRPN(tokens = ["4","13","5","/","+"])
target = 6
self.assertEqual(output, target)

def test_third_pattern(self):
solution = Solution()
output = solution.evalRPN(tokens = ["10","6","9","3","+","-11",
"*","/","*","17","+","5","+"])
target = 22
self.assertEqual(output, target)