Created
November 19, 2014 13:57
-
-
Save binhngoc17/319f3ec3c8daad56dac6 to your computer and use it in GitHub Desktop.
Evaluation of Postfix Expression
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
import sys | |
test_cases = open(sys.argv[1], 'r') | |
def eval_postfix(exp): | |
stack = [] | |
for i in exp: | |
try: | |
val = int(i) | |
stack.append(val) | |
except: | |
val1 = stack.pop() | |
val2 = stack.pop() | |
if i == '+': | |
val = val1 + val2 | |
elif i == '*': | |
val = val1 * val2 | |
elif i == '/': | |
val = val1 / val2 | |
stack.append(val) | |
return stack[-1] | |
for test in test_cases: | |
strs = test.replace('\n', '') | |
els = strs.split(' ') | |
print eval_postfix(els[::-1]) | |
test_cases.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment