Answer to Question #202029 in Python for S & Q - B

Question #202029

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

  1. a^b/c+d-(e/f-g+(h+i-j)^k+l-m/n)
  2. a/b^c^d+(e+f)/g^h-i*j/(k*l*m^n)
1
Expert's answer
2021-06-03T10:10:28-0400
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)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS