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.
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))
Comments
Leave a comment