in this tutorial we are learn about infix and postfix conversion and postfix evaluation
what is a infix and postfix?
basically infix is a expression are easily read and solve by humans, we can easily distinguish the order of operator , and also solving mathematically expression using parenthesis
the computer can not be differentiate operator and parenthesis easily that's why postfix is use
basically infix is use when an operator in between every pare of operand and postfix when an operator is followed for every pare of operand
the compiler scans the operation either right to left or left to right that's why postfix representation are use in
class Stack:
precedence={'^':5,'*':4,'/':4,'+':3.,'-':3,'(':2,')':1}
def __init__(self):
self.items=[]
self.size=-1
def push(self,value):
self.items.append(value)
self.size+=1
def pop(self):
if self.isEmpty():
return 0
else:
self.size-=1
return self.items.pop()
def isEmpty(self):
if(self.size==-1):
return True
else:
return False
def seek(self):
if self.isEmpty():
return False
else:
return self.items[self.size]
def isOperand(self,i):
if i in'ABCDEFGHIJKLMNOPQRSTUVWXYZ'or i in'0123456789':
return True
else:
return False
def infixtopostfix(self,expr):
postfix=""
print("postfix expression after every iteration is:")
for i in expr:
if(len(expr)%2==0):
print("incorrect infix expression")
return False
elif(self.isOperand(i)):
postfix+=i
elif(i in'+-*/^'):
while(len(self.items)and self.precedence[i]<=self.precedence[self.seek()]):
postfix+=self.pop()
self.push(i)
elif i is'(':
self.push(i)
elif i is')':
o=self.pop()
while o!='(':
postfix +=o
o=self.pop()
print(postfix)
while len(self.items):
if(self.seek()=='('):
self.pop()
else:
postfix+=self.pop()
return postfix
s=Stack()
choice=input("Press y to input expression and n to exit")
while(choice=='y'):
expr=input("Enter the expression")
result=s.infixtopostfix(expr)
if(result!=False):
print("The postfix expression of the infix expression:",expr,"is",result)
choice=input("Press y to input expression and n to exit")
b. Postfix Evaluation
class EvaluatePostfixExpr:
def __init__(self):
self.items=[]
self.size=-1
def push(self,value):
self.items.append(value)
self.size+=1
def pop(self):
if self.isEmpty():
return 0
else:
self.size-=1
return self.items.pop()
def isEmpty(self):
if(self.size==-1):
return True
else:
return False
def Evaluate(self,expr):
for i in expr:
if i in'0123456789':
self.push(i)
else:
op1=self.pop()
op2=self.pop()
result=self.calculate(op2,op1,i)
self.push(result)
return self.pop()
def calculate(self,op2,op1,i):
if i is'*':
return int(op2)*int(op1)
elif i is'/':
return int(op2)/int(op1)
elif i is'+':
return int(op2)+int(op1)
elif i is'-':
return int(op2)-int(op1)
elif i is'^':
return int(op2)^int(op1)
s=EvaluatePostfixExpr()
expr=input("Enter the postfix expression to be evaluated")
value=s.Evaluate(expr)
print("The result of the postfix exprssion",expr,"is",value)
0 Comments