Here is my implementation to convert Infix expression to Postfix expression
from ArrayStack import ArrayStack
class Convertor:
''' Class to convert the Infix exp into Postfix exp'''
def __init__(self,exp):
''' Constructor to initialize the class variable '''
self.infix = exp
self.stack = ArrayStack(len(exp))
def is_operand(self,sym):
''' Check if symbol is operand '''
return sym.isalpha()
def precedence(self,sym):
''' Returns the precedence of the operator'''
if sym == '+' or sym == '-':
return 1
elif sym == '*' or sym =='/':
return 2
elif sym == '^':
return 3
else:
return -1
def infix_to_postfix(self):
''' Converts the inifx exp into postfix exp '''
postfix = []
for i in self.infix:
if self.is_operand(i):
postfix.append(i)
elif i == '(':
self.stack.push(i)
elif i == ')':
while(not self.stack.is_empty() and self.stack.top() !='('):
postfix.append(self.stack.pop())
self.stack.pop()
else:
while (not self.stack.is_empty() and self.precedence(i) <= self.precedence(self.stack.top())):
postfix.append(self.stack.pop())
self.stack.push(i)
while (not self.stack.is_empty):
postfix.append(self.stack.pop())
postfix.append(self.stack.pop()) # I don't know why an element still existing in the stack , can any one help
print(postfix,len(postfix))
if __name__ == '__main__':
exp = "a+b*(c^d-e)^(f+g*h)-i"
print(exp,len(exp))
convertor = Convertor(exp)
convertor.infix_to_postfix()
I am not getting why my program is not able to pop the last element in the stack. I am doing it after the completion of the loop (look at the comment : line 55)
Please visit my github repo in needed :github repo