Answer to Question #202203 in Python for gositooo

Question #202203

Please provide the needed code of the question below, please avoid using 'def'.


Using the discussed methods, Convert the following Infix Expression to its equivalent Postfix and Prefix


Expression


1. a^b/c+d-(e/t-g+(h+i-j)^k+l-m/n)


2. a/b c d+e+f)/g^h-ij/(k'l'm^n)


1
Expert's answer
2021-06-05T02:12:08-0400
OPERATORS = set(['+', '-', '*', '/', '(', ')', '^'])  # set of operators


PRIORITY = {'+':1, '-':1, '*':2, '/':2, '^':3} # dictionary having priorities 


 
expression1 = "a^b/c+d-(e/t-g+(h+i-j)^k+l-m/n)"
# def infix_to_postfix(expression): #input expression


stack = [] # initially stack empty
output = '' # initially output empty


    


for ch in expression1:


    if ch not in OPERATORS:  # if an operand then put it directly in postfix expression


        output+= ch


    elif ch=='(':  # else operators should be put in stack


        stack.append('(')


    elif ch==')':


        while stack and stack[-1]!= '(':


            output+=stack.pop()


        stack.pop()


    else:


            # lesser priority can't be on top on higher or equal priority    


             # so pop and put in output   


        while stack and stack[-1]!='(' and PRIORITY[ch]<=PRIORITY[stack[-1]]:


            output+=stack.pop()


        stack.append(ch)


while stack:


    output+=stack.pop()




 
print('infix expression: ',expression1)


print('postfix expression: ',output)


#Converting postfix to prefix


# def postToPre(post_exp):
     
stack2 = []
 
    # length of expression
length = len(output)
 
    # reading from right to left
for i in range(length):
 
    # check if symbol is operator
       # if (isOperator(post_exp[i])):
        if output[i] in OPERATORS:
 
            # pop two operands from stack
            op1 = stack2[-1]
            stack2.pop()
            op2 = stack2[-1]
            stack2.pop()
 
            # concat the operands and operator
            temp = output[i] + op2 + op1
 
            # Push string temp back to stack
            stack2.append(temp)
 
        # if symbol is an operand
        else:
 
            # push the operand to the stack
            stack2.append(output[i])
 
    
ans = ""
for i in stack2:
        ans += i
print('Prefix expression is: ',ans)
 
# The second expression is not valid expression hence cannot be converted to prefixt nor postfix i.e it has ')' without opening one



My output is


infix expression: a^b/c+d-(e/t-g+(h+i-j)^k+l-m/n)

postfix expression: ab^c/d+et/g-hi+j-k^+l+mn/--

Prefix expression is: -+/^abcd-++-/etg^-+hijkl/mn


[Program finished]


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