Reputation: 1
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.
Upvotes: 0
Views: 393
Reputation: 1146
Actually, 10
is the correct answer. Stack is a LIFO (Last In, First Out) structure which is, with a Python implementation, simply an inherited list
class with push==append
(add an element to the end) and pop
which remove the last element of the list.
Step 1: c=(2) ; Stack = [] ; action = Push(2) ; Stack = [2]
Step 2: c=(3) ; Stack = [2] ; action = Push(3) ; Stack = [2, 3]
Step 3: c=(4) ; Stack = [2, 3] ; action = Push(4) ; Stack = [2, 3, 4]
Step 4: c=(*) ; Stack = [2, 3, 4] ; action = Push(Pop(4) * Pop(3)) ; Stack = [2, 12]
Step 5: c=(-) ; Stack = [2, 12] ; action = Push(Pop(12) - Pop(2)) ; Stack = [10]
Upvotes: 0