Created
September 30, 2020 03:49
-
-
Save Abhayparashar31/3f552bb5c7a0a5b9ac6e3cb69b284c57 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
OPERATORS = set(['+', '-', '*', '/', '(', ')', '^']) # set of operators | |
PRIORITY = {'+':1, '-':1, '*':2, '/':2, '^':3} # dictionary having priorities | |
def infix_to_postfix(expression): #input expression | |
stack = [] # initially stack empty | |
output = '' # initially output empty | |
for ch in expression: | |
if ch not in OPERATORS: # if an operand then put it directly in postfix expression | |
output+= ch | |
elif ch == '(' : # else operators should be put in stack | |
stack.append('(') | |
elif ch==')': | |
while stack and stack[-1]!= '(': | |
output+=stack.pop() | |
stack.pop() | |
else: | |
# lesser priority can't be on top on higher or equal priority | |
# so pop and put in output | |
while stack and stack[-1]!='(' and PRIORITY[ch]<=PRIORITY[stack[-1]]: ## Comparing the operator with the top of stack | |
output+=stack.pop() ## pop the lesser priority operator and show it in output | |
stack.append(ch) ## PUSH the higher priority operator onto stack | |
while stack: | |
output+=stack.pop() ## Pop each element from the stack one by one and show them in output at the end | |
return output ## Return the postfix expression | |
expression = input('Enter infix expression') ## enter infix expression | |
print('infix expression: ',expression) ## printing the intfix expression | |
print('postfix expression: ',infix_to_postfix(expression)) ## printing the post fix expression | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment