Skip to content

Instantly share code, notes, and snippets.

@taylorsmithgg
Created November 10, 2017 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taylorsmithgg/bbce4639811eca4b1e99479273115072 to your computer and use it in GitHub Desktop.
Save taylorsmithgg/bbce4639811eca4b1e99479273115072 to your computer and use it in GitHub Desktop.
from pythonds.basic.stack import Stack
def postfixEval(postfixExpr):
operandStack = Stack()
tokenList = postfixExpr.split()
for token in tokenList:
if token in "0123456789":
operandStack.push(int(token))
else:
operand2 = operandStack.pop()
operand1 = operandStack.pop()
result = doMath(token,operand1,operand2)
operandStack.push(result)
return operandStack.pop()
def doMath(op, op1, op2):
if op == "*":
return op1 * op2
elif op == "/":
return op1 / op2
elif op == "+":
return op1 + op2
else:
return op1 - op2
print(postfixEval('7 8 + 3 2 + /'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment