0% found this document useful (0 votes)
278 views

Infix Prefix Python Code

This document contains a Python program to convert an infix notation mathematical expression to postfix notation. It uses a stack and list to evaluate the precedence of operators and convert the expression. The program takes an infix expression as input, iterates through each character and sends it to a function to determine if it is an operand, operator, or bracket. Based on the operator precedence, it either adds operands to a list or pushes operators to a stack to generate the postfix expression, which is then printed.

Uploaded by

varun
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
278 views

Infix Prefix Python Code

This document contains a Python program to convert an infix notation mathematical expression to postfix notation. It uses a stack and list to evaluate the precedence of operators and convert the expression. The program takes an infix expression as input, iterates through each character and sends it to a function to determine if it is an operand, operator, or bracket. Based on the operator precedence, it either adds operands to a list or pushes operators to a stack to generate the postfix expression, which is then printed.

Uploaded by

varun
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

#INFIX TO POSTFIX

Stack=[]
Exp=[]
order={'(':1,')':1,'**':4,'//':3,'%':3,'/':3,'*':3,'+':2,'-':2}
def send(item,end=False):
if not end:
if item.isalpha():
Stack.append(item)
else:
if (not Exp) and item!='(':
Exp.append(item)
elif item==')':
Exp.reverse()
i=0
while i<len(Exp):
if Exp[i]!='(':
Stack.append(item)
print Exp
i+=1
else:
del Exp[i]
break
Exp.reverse()
elif order[Exp[-1]]>order[item]:
Stack.append(Exp[-1])
del Exp[-1]
Exp.append(item)
else:
Exp.append(item)
else:
Stack.append(item)
Exp.reverse()
for i in Exp:
Stack.append(i)
def printer(S):

#S is Stack
print ''.join(S)
def main():
global Stack
global Exp
while True:
a=raw_input('ENTER CHARACTER BASED INFIX EXPRESSION \n')
a=list(a)
#CONVERT TO LIST
for i in range(len(a)):
if i==len(a)-1:
send(a[i],True)
else:
send(a[i])
print 'FINAL EXPRESSION :'
printer(Stack)
Exp=[]
Stack=[]
q=raw_input('PRESS Q TO QUIT')
if q.upper()=='Q':
break
if __name__=='__main__':
main()

You might also like