I want to write a Python code that will evaluate an expression using stack. I have the following code, where numStk is a stack that holds number and optStk that holds operators. In the expression 2+3*4-6, at the end of for loop, numStack contains 2, 12, and 6; and optStk contains - and +. Now how can I make my setOps() function to pop elements from the two stacks to do the evaluate the expression?
def main():
raw_expression = input("Enter an expression: ")
expression = raw_expression.replace(" ", "")
for i in expression:
if (i in numbers):
numStk.push(i)
else:
setOps(i)
optStk.push(i)
## code needed to evaluate the rest of the elements in stackstack
return valStk.top()
My setOps(i) function is as follow:
def repeatOps(refOp):
while (len(valStk) > 1 and operators.index(refOp) <= operators.index(optStk.top())):
x = numStk.pop()
y = numStk.pop()
op = optStk.pop()
numStk.push(str(eval(x+op+y)))