|
| 1 | +class Stack(object): |
| 2 | + """ A simple stack ADT with top as the end of a list """ |
| 3 | + def __init__(self): |
| 4 | + self.items = [] |
| 5 | + |
| 6 | + def __str__(self): |
| 7 | + return ("Stack of size: %d" % len(self.items)) |
| 8 | + |
| 9 | + def isEmpty(self): |
| 10 | + return len(self.items) == 0 |
| 11 | + |
| 12 | + def push(self, item): |
| 13 | + self.items.append(item) |
| 14 | + |
| 15 | + def pop(self): |
| 16 | + return self.items.pop() |
| 17 | + |
| 18 | + def top(self): |
| 19 | + if self.isEmpty(): return None |
| 20 | + return self.items[len(self.items)-1] |
| 21 | + |
| 22 | +def string_reverse(s): |
| 23 | + stack = Stack() |
| 24 | + rev = [] |
| 25 | + for c in s: stack.push(c) |
| 26 | + while not stack.isEmpty(): |
| 27 | + rev.append(stack.pop()) |
| 28 | + return "".join(rev) |
| 29 | + |
| 30 | +def match_paren(parens): |
| 31 | + """ returns true or false if parenthesis |
| 32 | + expression passed is matching""" |
| 33 | + stack = Stack() |
| 34 | + for b in parens: |
| 35 | + if b == "(": |
| 36 | + stack.push(1) |
| 37 | + else: # b == ")" |
| 38 | + if not stack.isEmpty(): |
| 39 | + stack.pop() |
| 40 | + else: |
| 41 | + return False |
| 42 | + return stack.isEmpty() |
| 43 | + |
| 44 | + |
| 45 | +def infix_to_postfix(infixexpr): |
| 46 | + prec = { '+': 2, '-': 2, '*': 3, '/': 3,'(': 1 } # denoting precedence |
| 47 | + operator_stack = Stack() |
| 48 | + operators = "+-*/()" |
| 49 | + output_list = [] |
| 50 | + for token in infixexpr.split(): |
| 51 | + if token not in operators: |
| 52 | + output_list.append(token) |
| 53 | + elif token == "(": |
| 54 | + operator_stack.push("(") |
| 55 | + elif token == ")": |
| 56 | + topToken = operator_stack.pop() |
| 57 | + while topToken != "(": |
| 58 | + output_list.append(topToken) |
| 59 | + topToken = operator_stack.pop() |
| 60 | + else: # an operator |
| 61 | + while (not operator_stack.isEmpty()) and \ |
| 62 | + (prec[operator_stack.top()] >= prec[token]): |
| 63 | + output_list.append(operator_stack.pop()) |
| 64 | + operator_stack.push(token) |
| 65 | + |
| 66 | + # tokens exhausted - empty out the stack |
| 67 | + while not operator_stack.isEmpty(): |
| 68 | + output_list.append(operator_stack.pop()) |
| 69 | + return " ".join(output_list) |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + expr = ["A * B + C * D", "( A + B ) * C - ( D - E ) * ( F + G )"] |
| 74 | + for e in expr: |
| 75 | + print infix_to_postfix(e) |
0 commit comments