Created
December 13, 2011 16:20
-
-
Save thinkphp/1472745 to your computer and use it in GitHub Desktop.
Postfix math evaluator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ''' | |
| 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