def infix2prefix(expression): res_stack = LinkedStack() op_stack = LinkedStack() op_priority = {'*': 2, '/': 2, '%': 2, '+': 1, '-': 1, '(': 0, ')': 0} width = 7 if len(expression) <= 7 else len(expression) print(expression[::-1]) print('Symbol'.center(8), 'op_stack'.center(width), 'res_stack'.center(width), sep=" | ") print('-' * (width * 3 + 7)) for e in reversed(expression): if e == ')': op_stack.push(e) elif e == '(': while op_stack.first() != ')': res_stack.push(op_stack.pop()) op_stack.pop() elif e.isdigit(): res_stack.push(e) else: while op_stack.first( ) and op_priority[e] <= op_priority[op_stack.first()]: res_stack.push(op_stack.pop()) op_stack.push(e) print_stack(e, op_stack, res_stack, width) while not op_stack.is_empty(): res_stack.push(op_stack.pop()) print_stack(' ', op_stack, res_stack, width) output = '' while not res_stack.is_empty(): output += res_stack.pop() return output
def infix2postfix(expression): output = [] op_stack = LinkedStack() op_priority = {'*': 2, '/': 2, '%': 2, '+': 1, '-': 1, '(': 0, ')': 0} for e in expression: if e == '(': op_stack.push(e) elif e == ')': while op_stack.first() != '(': output.append(op_stack.pop()) op_stack.pop() elif e.isdigit(): output.append(e) else: while not op_stack.is_empty() and op_priority[op_stack.first()] >= op_priority[e]: output.append(op_stack.pop()) op_stack.push(e) while not op_stack.is_empty(): output.append(op_stack.pop()) return ''.join(output)