Skip to content

Instantly share code, notes, and snippets.

@chrisstpierre
Created October 8, 2020 02:50
Show Gist options
  • Save chrisstpierre/d110b758bac698b3b872f6c4fbb10b4d to your computer and use it in GitHub Desktop.
Save chrisstpierre/d110b758bac698b3b872f6c4fbb10b4d to your computer and use it in GitHub Desktop.
Infix Expression Evaluation
def evaluate(e):
expr = list(e)
stack = []
num=""
while len(expr) > 0:
c = expr.pop(0)
if c in "0123456789." or (c is "-" and (len(stack) == 0 or str(stack[-1]) in "+-*/")):
num += c
else:
if num:
stack.append(num)
num = ""
if c in "+-*/":
stack.append(c)
elif c == ")" and len(stack) >= 3:
num2 = stack.pop()
operator = stack.pop()
num1 = stack.pop()
if operator is "+":
stack.append(float(num1) + float(num2))
elif operator is "-":
stack.append(float(num1) - float(num2))
elif operator is "/":
if num2 == 0:
return "ERROR"
stack.append(float(num1) / float(num2))
elif operator is "*":
stack.append(float(num1) * float(num2))
if len(stack) > 1:
return "ERROR"
result = stack.pop()
if result.is_integer():
return int(result)
else:
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment