Skip to content

Instantly share code, notes, and snippets.

@mvallebr
Created October 16, 2014 02:14
Show Gist options
  • Save mvallebr/1b2f1da6e392d08f61c8 to your computer and use it in GitHub Desktop.
Save mvallebr/1b2f1da6e392d08f61c8 to your computer and use it in GitHub Desktop.
post fix expression evaluation
'''
Created on 15/10/2014
@author: mvalle
'''
import unittest
from decimal import Decimal
OPS = {
'+': Decimal.__add__,
'-': Decimal.__sub__,
'*': Decimal.__mul__,
'/': Decimal.__div__,
}
def postfix_evaluate(expression):
s = []
operand = 0
has_digit = False
for c in expression.strip():
if c == ' ':
if has_digit:
s.append(operand)
operand = 0
has_digit = False
elif c.isdigit():
operand = 10 * operand + int(c)
has_digit = True
elif c in '*/+-':
s.append(OPS[c](Decimal(s.pop()), Decimal(s.pop())))
else:
raise "Invalid char in expression"
return s.pop()
class PostfixTest(unittest.TestCase):
def test1(self):
result = postfix_evaluate('2 3 * 5 +')
print "test1 result =", result
assert (result == 11)
def test2(self):
result = postfix_evaluate('2 3 * 6 + 15 20 10 + * /')
print "test2 result =", result
assert (result == Decimal(37.5))
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment