Evaluate Postfix Expression.

Evaluate Postfix Expression. 


Problem: 

Accept a postfix expression, evaluate it and print the result. 

Input: 

10 3 1 * + 9 -

Output: 

4

Program:

s = input().split() 

stack = [] 

for i in s: 

    if i.isdigit(): 

        stack.append(int(i)) 

    else: 

        b = stack.pop() 

        a = stack.pop() 

        if i == '+': 

            stack.append(a+b) 

        elif i == '-': 

            stack.append(a-b) 

        elif i == '*': 

            stack.append(a*b) 

        elif i == '/':

            stack.append(a//b)

print(*stack)

Explanation: 

1. Accept a string S (postfix expression) and split the string with respect to the whitespace.

2. Create an empty stack. 

3. Iterate the string,

      a.  if an integer is encountered, push into the stack.

      b.  if any symbol in { +, -, /, *} is encountered, pop the top of the stack twice, perform the corresponding operation and push it to stack. 

4.  Repeat the step 3 until the end of the string is reached. 

5. Finally, print the content of the stack.

Comments

Popular posts from this blog

Pronic Integers in N - InfyTQ question

Count Strong Points - Accenture

Letters at position of multiples of a number