Answer to Question #203865 in Python for Rijak

Question #203865

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!


The infix is given below. 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)
1
Expert's answer
2021-06-06T08:56:29-0400
s = 'a/b^c^d+(e+f)/g^h-i*j/(k*l*m^n)'
# infix t postfix
priority = {'(': 1, '-': 2, '+': 2, '/': 3, '*': 3, '^': 4}
opstack = []
output = []
for token in s:
    if token.isalpha():
        output.append(token)
    elif token == '(':
        opstack.append(token)
    elif token == ')':
        top_token = opstack.pop()
        while top_token != '(':
            output.append(top_token)
            top_token = opstack.pop()
    elif token in priority.keys():
        while opstack and (priority[opstack[-1]] >= priority[token]):
            output.append(opstack.pop())
        opstack.append(token)
while opstack:
    output.append(opstack.pop())
print('Infix: ', s, 'Postfix: ', ''.join(output))
# postfix to prefix
opstack = []
for token in output:
    if token in '+-*/^':
        temp = token + opstack.pop(-2) + opstack.pop()
        opstack.append(temp)
    else:
        opstack.append(token)
print('Infix: ', s, 'Prefix: ', ''.join(opstack))

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