Let us take an Expression - "231*+9-".
1. We will push only integers into Stack, and when an operator is encountered, we perform operation on operands.
2. First stack contains '2' - push it.
3. Scan '3' it is a number push it to Stack. Now, stack contains '2 3'.
4. Scan '1' it is a number push it to Stack. Stack contains '2 3 1'.
5. Scan '*', now it's an operator, pop two operands from stack, and perform multiplication (3*1) becomes 3. Now, push the result into stack. And stack becomes '2 3'.
6. Scan '+' again it's an operator pop two operands from stack, and perform operation. Result is
2+3 = 5, push it to Stack.
7. Scan '9' its an integer push it to stack. Now stack is '5 9'.
8. Scan '-' pop two operands from stack, and the result is (5-9 = -4). Push it to Stack.
9. Since, there are no more elements left to Scan, return the top element of Stack, or pop the element from stack and print it.
which is the answer.
def postfix(string, stack):
for i in string: | |
if 48<=ord(i)<=57: | |
stack.push(i) | |
else: | |
if stack.isEmpty()==False: | |
p = stack.pop() | |
q = stack.pop() | |
p = int(p) | |
q = int(q) | |
if i=='+': | |
stack.push(p+q) | |
if i=='-': | |
stack.push(q-p) | |
if i=='/': | |
stack.push(q//p) | |
if i=='*': | |
stack.push(p*q) | |
return stack.top() |
Comments
Post a Comment