Skip to content

Instantly share code, notes, and snippets.

@hgenru
Last active August 29, 2015 14:02
Show Gist options
  • Save hgenru/48c7b0f965f6d239e091 to your computer and use it in GitHub Desktop.
Save hgenru/48c7b0f965f6d239e091 to your computer and use it in GitHub Desktop.
Reverse Polish Notation (python)
OPERATORS = {
'*': lambda a, b: a * b,
'/': lambda a, b: a / b,
'+': lambda a, b: a + b,
'-': lambda a, b: a - b
}
def polish_eval(exp):
exp_list = exp.split(' ')
stack = []
for item in exp_list:
if item in OPERATORS:
b = stack.pop()
a = stack.pop()
result = OPERATORS[item](a, b)
stack.append(result)
else:
stack.append(int(item))
return stack.pop()
from unittest import TestCase
from rpn import polish_eval
class TestReversePolishNotation(TestCase):
def test_simple_addition(self):
self.assertEqual(47, polish_eval('12 35 +'))
self.assertEqual(4, polish_eval('2 2 +'))
self.assertEqual(1, polish_eval('-1 2 +'))
def test_simple_subtraction(self):
self.assertEqual(1, polish_eval('2 1 -'))
self.assertEqual(5, polish_eval('2 -3 -'))
self.assertEqual(1, polish_eval('-1 -2 -'))
def test_simple_multiplication(self):
self.assertEqual(4, polish_eval('2 2 *'))
self.assertEqual(9, polish_eval('-3 -3 *'))
self.assertEqual(-8, polish_eval('-2 4 *'))
def test_simple_division(self):
self.assertEqual(4, polish_eval('8 2 /'))
self.assertEqual(-2, polish_eval('-4 2 /'))
self.assertEqual(3, polish_eval('-6 -2 /'))
def test_multi_operators(self):
self.assertEqual(4, polish_eval('3 4 - 5 +'))
self.assertEqual(14, polish_eval('5 1 2 + 4 * + 3 -'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment