Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created December 13, 2011 16:20
Show Gist options
  • Select an option

  • Save thinkphp/1472745 to your computer and use it in GitHub Desktop.

Select an option

Save thinkphp/1472745 to your computer and use it in GitHub Desktop.
Postfix math evaluator
'''
Postfix math evaluator
See: http://en.wikipedia.org/wiki/Reverse_Polish_notation
by Adrian Statescu <mergesortv@gmail.com>
MIT Style License
'''
import re
operators = {'+': lambda x,y: x+y,
'*': lambda x,y: x*y,
'/': lambda x,y: x/y,
'-': lambda x,y: x-y}
def postfixeval(str):
stack = []
n = len(str)
ch = None
for i in range(0,n):
ch = str[i]
if re.match('\d',ch):
stack.append(int(ch))
elif ch in operators:
a = stack.pop(-1)
b = stack.pop(-1)
val = operators[ch](a,b)
stack.append(val)
return stack[0]
print postfixeval("2 3 + 7 * 3 *")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment