what I have so far is:
Stack = ArrayStack()
def evaluate(postfix_str, Stack):
for c in postfix_str:
if c not in '+-*/()':
Stack.push(int(c))
else:
c.split(" ")
if c == '+':
sum = Stack.pop() + Stack.pop()
Stack.push(sum)
elif c == '-':
difference = Stack.pop() - Stack.pop()
Stack.push(difference)
elif c == '*':
product = Stack.pop() * Stack.pop()
Stack.push(product)
elif c == '/':
quotient = Stack.pop() / Stack.pop()
Stack.push(quotient)
else:
Stack.push(int(c))
return Stack.pop()
print(evaluate('234*-', Stack)) # 10
This code is supposed to find an operator, pop its operands off the stack, run the operation and then push the result back on the stack. but when I run my code let's say one of my test cases is ('234*-'), so instead of getting -10, what I am getting is 10.
c.split(" "). It produces a result which you then immediately discard, so it has no effect. Change it or delete it.Stack.pop()twice in an expression, it is performing them left-to-right. So the left operand is the last value you pushed, and the right operand is the one before that. That's backwards from what you want. The first value you pop should be the right operand, and the second should be the left. Simple. You wantval2 = Stack.pop(); val1 = Stack.pop()