|
| 1 | +import string |
| 2 | + |
| 3 | +from Stack import Stack |
| 4 | + |
| 5 | +__author__ = 'Omkar Pathak' |
| 6 | + |
| 7 | + |
| 8 | +def is_operand(char): |
| 9 | + return char in string.ascii_letters or char in string.digits |
| 10 | + |
| 11 | + |
| 12 | +def precedence(char): |
| 13 | + """ Return integer value representing an operator's precedence, or |
| 14 | + order of operation. |
| 15 | +
|
| 16 | + https://en.wikipedia.org/wiki/Order_of_operations |
| 17 | + """ |
| 18 | + dictionary = {'+': 1, '-': 1, |
| 19 | + '*': 2, '/': 2, |
| 20 | + '^': 3} |
| 21 | + return dictionary.get(char, -1) |
| 22 | + |
| 23 | + |
| 24 | +def infix_to_postfix(expression): |
| 25 | + """ Convert infix notation to postfix notation using the Shunting-yard |
| 26 | + algorithm. |
| 27 | +
|
| 28 | + https://en.wikipedia.org/wiki/Shunting-yard_algorithm |
| 29 | + https://en.wikipedia.org/wiki/Infix_notation |
| 30 | + https://en.wikipedia.org/wiki/Reverse_Polish_notation |
| 31 | + """ |
| 32 | + stack = Stack(len(expression)) |
| 33 | + postfix = [] |
| 34 | + for char in expression: |
| 35 | + if is_operand(char): |
| 36 | + postfix.append(char) |
| 37 | + elif char not in {'(', ')'}: |
| 38 | + while (not stack.is_empty() |
| 39 | + and precedence(char) <= precedence(stack.peek())): |
| 40 | + postfix.append(stack.pop()) |
| 41 | + stack.push(char) |
| 42 | + elif char == '(': |
| 43 | + stack.push(char) |
| 44 | + elif char == ')': |
| 45 | + while not stack.is_empty() and stack.peek() != '(': |
| 46 | + postfix.append(stack.pop()) |
| 47 | + # Pop '(' from stack. If there is no '(', there is a mismatched |
| 48 | + # parentheses. |
| 49 | + if stack.peek() != '(': |
| 50 | + raise ValueError('Mismatched parentheses') |
| 51 | + stack.pop() |
| 52 | + while not stack.is_empty(): |
| 53 | + postfix.append(stack.pop()) |
| 54 | + return ' '.join(postfix) |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == '__main__': |
| 58 | + expression = 'a+b*(c^d-e)^(f+g*h)-i' |
| 59 | + |
| 60 | + print('Infix to Postfix Notation demonstration:\n') |
| 61 | + print('Infix notation: ' + expression) |
| 62 | + print('Postfix notation: ' + infix_to_postfix(expression)) |
0 commit comments