Skip to content

Instantly share code, notes, and snippets.

@binhngoc17
Created November 19, 2014 13:57
Show Gist options
  • Save binhngoc17/319f3ec3c8daad56dac6 to your computer and use it in GitHub Desktop.
Save binhngoc17/319f3ec3c8daad56dac6 to your computer and use it in GitHub Desktop.
Evaluation of Postfix Expression
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