MontaKr
MontaKr

Reputation: 155

How can I change order of calculation in stack algorithm?

Hi I'm trying to make postfix increment operator by using simple stack algorithm. If I input 20 4 /, I need to get result of 5. But in my code, the last input comes first so the result becomes 0.2. How can I make it while maintaining my form??

class stackcl:
   def __init__(self):
       self.items = []
   def push(self, item):
       self.items.append(item)
   def pop(self):
       return self.items.pop()

arr = stackcl()
str = input().split()
x = 0

for c in str:
   x = 0
   elif c == '/':
       x = arr.pop() / arr.pop()
   elif c >= '0' and c <= '9':
       x = 10 * c + c
       c = int(c)
   arr.push(c)

x = arr.pop()
print(x)

Upvotes: 0

Views: 65

Answers (1)

farukcolak
farukcolak

Reputation: 76

Stacks works as LIFO (Last In, First Out). So, when you push something to stack, you push it to the top of the stack. When you pop something from the stack, you get the element at the top of the stack (last pushed element).

I think the first element of "str" is 20. But there is no suitable case in if statements for 20. So it is pushed to stack.

Now stack is : 20

Then 4 comes, and it is pushed onto stack.

Now stack is : (Bottom) 20 -> 4 (Top).

Then "/" comes and below line works.

elif c == '/':
       x = arr.pop() / arr.pop()

First pop function pops 4 from stack because it is on the top. Then second pop function pops 20 from stack. 4 / 20 = 0.2 :)

EDIT

To make it work, maybe you can try this;

elif c == '/':
    lastElement = arr.pop() // which is 4
    firstElement = arr.pop() // which is 20
    x = firstElement / lastElement  // 20 / 4 = 5

Upvotes: 1

Related Questions