My program is supposed to evaluate given infix expressions and evaluate them. It is assumed that only the operators in the method calls at the bottom of the code will be used for any given infix expressions that would be run by the program.
from pythonds.basic.stack import Stack
import operator
def infixToValue(expr):
prec = {}
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["≤"] = 1
prec["$"] = 0
opStack = Stack()
valStack = Stack()
ops = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, "≤": operator.le}
opList = ["+", "-", "*", "/", "≤"]
tokens = expr.split()
def doOp():
x = int(valStack.pop())
y = int(valStack.pop())
op = ops[opStack.pop()]
valStack.push(op(x, y))
def repeatOps(refOp):
while valStack.size() > 1 and opStack.size() > 0 and prec[refOp] <= prec[opStack.peek()]:
doOp()
for token in tokens:
if token.isdigit():
valStack.push(token)
else:
repeatOps(token)
opStack.push(token)
repeatOps("$")
return valStack.pop()
print(infixToValue('14 - 3 * 2 + 7'))
print(infixToValue('14 ≤ 4 - 3 * 2 + 7'))
print(infixToValue('15 + 16 – 2 + 7 * 3 * 2 – 14'))
The current output is the following:
C:\Users\skarl\AppData\Local\Programs\Python\Python37\python.exe C:/Users/skarl/PycharmProjects/Project02/Root.py
Traceback (most recent call last):
File "C:/Users/skarl/PycharmProjects/Project02/Root.py", line 40, in <module>
-1
print(infixToValue('15 + 16 – 2 + 7 * 3 * 2 – 14'))
True
File "C:/Users/skarl/PycharmProjects/Project02/Root.py", line 32, in infixToValue
repeatOps(token)
File "C:/Users/skarl/PycharmProjects/Project02/Root.py", line 25, in repeatOps
while valStack.size() > 1 and opStack.size() > 0 and prec[refOp] <= prec[opStack.peek()]:
KeyError: '–'
Process finished with exit code 1
The -1 seems to be the result for the first infix expression, which is arithmetically incorrect, as well as a KeyError for my "-" on the second expression which was referenced in the first infix expression. What flaws are making my code work incorrectly?
The –
characters in your third call:
print(infixToValue('15 + 16 – 2 + 7 * 3 * 2 – 14'))
are actually the Unicode U+2013 character (en dash).
Your code would work fine if you replace both en dash characters with ASCII -
signs:
print(infixToValue('15 + 16 - 2 + 7 * 3 * 2 - 14'))