|
| 1 | +class Stack: |
| 2 | + def __init__(self): |
| 3 | + self.stack = [] |
| 4 | + def push(self, item): |
| 5 | + self.stack.append(item) |
| 6 | + def pop(self): |
| 7 | + return self.stack.pop() |
| 8 | + def isEmpty(self): |
| 9 | + return self.stack == [] |
| 10 | + def peek(self): |
| 11 | + return self.stack[self.size() - 1 ] |
| 12 | + def size(self): |
| 13 | + return len(self.stack) |
| 14 | + |
| 15 | +def infix2postFix(string): |
| 16 | + opStack = Stack() |
| 17 | + result = "" |
| 18 | + expression = string.split(" ") |
| 19 | + |
| 20 | + for x in expression: |
| 21 | + if x == "(": |
| 22 | + opStack.push(x) |
| 23 | + elif x == ")": |
| 24 | + if opStack.peek() == "(": |
| 25 | + opStack.pop() |
| 26 | + else: |
| 27 | + while(opStack.peek() != "("): |
| 28 | + result+=opStack.pop() + " " |
| 29 | + opStack.pop() |
| 30 | + elif x in "abcdefghijklmnopqrstuvwxyz" or x in "1234567890": |
| 31 | + result += x + " " |
| 32 | + |
| 33 | + elif x in "+-/*" and opStack.size() > 0: |
| 34 | + if opStack.peek() in "*/+-": |
| 35 | + while(prec[opStack.peek()] >= prec[x]): |
| 36 | + result+=opStack.pop() + " " |
| 37 | + opStack.push(x) |
| 38 | + |
| 39 | + elif x in "+-/*" and opStack.size() == 0: |
| 40 | + opStack.push(x) |
| 41 | + |
| 42 | + stackLeft = opStack.size() |
| 43 | + while(stackLeft > 0): |
| 44 | + stackLeft -=1 |
| 45 | + result += opStack.pop() + " " |
| 46 | + |
| 47 | + return result[:-1] |
| 48 | + |
| 49 | + |
| 50 | +def evaluatePostFix(expression): |
| 51 | + listExpression = expression.split(" ") |
| 52 | + operandStack = Stack() |
| 53 | + operatorStack = Stack() |
| 54 | + |
| 55 | + for x in listExpression: |
| 56 | + if x in "1234567890": |
| 57 | + operandStack.push(x) |
| 58 | + elif x in "*/+-": |
| 59 | + operatorStack.push(x) |
| 60 | + |
| 61 | + |
| 62 | + while(operatorStack.size() > 0): |
| 63 | + a = int(operandStack.pop()) |
| 64 | + b = int(operandStack.pop()) |
| 65 | + |
| 66 | + sym = operatorStack.pop() |
| 67 | + |
| 68 | + if sym == "+": |
| 69 | + operandStack.push(a+b) |
| 70 | + elif sym == "-": |
| 71 | + operandStack.push(a-b) |
| 72 | + elif sym == "/": |
| 73 | + operandStack.push(a/b) |
| 74 | + elif sym == "*": |
| 75 | + operandStack.push(a*b) |
| 76 | + |
| 77 | + return operandStack.pop() |
| 78 | + |
| 79 | +exp = raw_input("Enter = ") |
| 80 | +print(evaluatePostFix(infix2postFix(exp))) |
0 commit comments