Can you please provide the code, with this question below. Please don't use def in doing the code, please do a simple one. Thankyou!
Using the discussed methods, Convert the following Infix Expression to its equivalent Postfix and Prefix Expression
ops= set(['+', '-', '*', '/', '(', ')', '^'])
pri= {'+':1, '-':1, '*':2, '/':2, '^':3}
#exp="a^b/c+d-(e/f-g+(h+i-j)^k+l-m/n)"
exp= input('Enter infix expression: ')
#infix_to_postfix
stack1 = []
output1 = ''
for c in exp:
if c not in ops:
output1+= c
elif c=='(':
stack1.append('(')
elif c==')':
while stack1 and stack1[-1]!= '(':
output1+=stack1.pop()
stack1.pop()
else:
while stack1 and stack1[-1]!='(' and pri[c]<=pri[stack1[-1]]:
output1+=stack1.pop()
stack1.append(c)
while stack1:
output1+=stack1.pop()
print('infix expression: ',exp)
print('postfix expression: ',output1)
#infix_to_prefix
exp= list(exp[::-1])
for i in range(len(exp)):
if exp[i] == "(":
exp[i] = ")"
elif exp[i] == ")":
exp[i] = "("
exPre="".join(exp)
stack2 = []
output2 = ''
for c in exPre:
if c not in ops:
output2+= c
elif c=='(':
stack2.append('(')
elif c==')':
while stack2 and stack2[-1]!= '(':
output2+=stack2.pop()
stack2.pop()
else:
while stack2 and stack2[-1]!='(' and pri[c]<=pri[stack2[-1]]:
output2+=stack2.pop()
stack2.append(c)
while stack2:
output2+=stack2.pop()
output2=output2[::-1]
print('prefix expression: ',output2)
Comments
Leave a comment