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.
Actually,
10is the correct answer. Stack is a LIFO (Last In, First Out) structure which is, with a Python implementation, simply an inheritedlistclass withpush==append(add an element to the end) andpopwhich remove the last element of the list.