0

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.

3
  • This statement makes no sense: c.split(" "). It produces a result which you then immediately discard, so it has no effect. Change it or delete it. Commented Oct 7, 2022 at 23:33
  • Also, your bug is obvious: When you use 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 want val2 = Stack.pop(); val1 = Stack.pop() Commented Oct 7, 2022 at 23:37
  • thank you. That definitely makes more sense. I am a beginner, this is like my first time taking a python class, so I appreciate the help. Commented Oct 8, 2022 at 0:10

1 Answer 1

0

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] 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.