Hey guys,
Hope you all are doing great.
Please let me know your feedback, on how i can improve and make it better. Till then!! Cheers!!
Algorithm To Convert Post-fix Expression into Infix expression:-
- Scan the Post-fix String from Left to Right.
- If the character is an Operand, then Push it on to the deque.
- If the character is an Operator, then Pop left Operator 1 and Operand 2 and concatenate them using Infix notation where the Operator is in between the Two Operands.
- The resultant expression is then pushed on the deque.
- Repeat the above steps till the Post-fix string is not scanned completely.
- Use parentheses properly to ensure correct order for evaluating the final expression.
Code Implementation:-
# -*- coding: utf-8 -*- """ Created on Wed Dec 22 22:58:14 2018 @author: Kurtesy """ from collections import deque OPERATORS = '+-/*' def postfix_to_infix(my_queue): if len(my_queue) == 1: return my_queue variable_1 = my_queue.popleft() """Handles left to right operation""" if variable_1 in OPERATORS: operand2 = my_queue.pop() operand1 = my_queue.pop() my_queue.append(('(%s)' % ''.join([operand1, variable_1, operand2]))) return postfix_to_infix(my_queue) """Handles previous expression and next operand""" variable_2 = my_queue.popleft() if variable_2 in OPERATORS: operand1 = my_queue.pop() my_queue.append(('(%s)' % ''.join([operand1, variable_2, variable_1]))) return postfix_to_infix(my_queue) """Process complete expression""" operation = my_queue.popleft() my_queue.append(('(%s)' % ''.join([variable_1, operation, variable_2]))) return postfix_to_infix(my_queue) def func(x): return eval() while 1: expression = input() """Input till # is enforced""" if '#' in expression: break queue = deque(expression) postfix = postfix_to_infix(queue) print(postfix.pop())
Please let me know your feedback, on how i can improve and make it better. Till then!! Cheers!!
Add a comment