Can you please rewrite the code below. Please, thank you. This is the question:
Create a program that will convert an infix expression entered by the user to its equivalent prefix and postfix expression Sample Output: Enter an Infix Expression: a+b^(c^d- e/(f+g)+(h^i)^j) <input> Postfix Expression: abcd^efg+/- hi^j^+^+ <compute> Prefix Expression: +a^b+- ^cd/e+fg^^hij <compute>
prefix = input("Enter an Infix Expression: ')
infixstack = []
x = len(prefix)
for i in range (x) :
index = (x-1)-i
if prefix[index == " + " or prefix[index] == "-" or prefix[index] == "-" or prefix[index] == "*':
op1 = infixstack.pop()
op2 = infixstack.pop()
Infix = "(" op1 + " " + prefix[index] + " " + op2 + ")"
infixstack.append(Infix)
else:
ifixstack.append(prefix[index])
print(*infixstack)
def inf2post(s):
var = set('abcdefghijklmnopqrstuvwxyz')
op = {'+':0, '-':0, '*':1, '/':1, '^':2}
ops = []
postfix = []
for ch in s:
if ch == ' ':
continue
if ch in var:
postfix.append(ch)
elif ch == '(':
ops.append(ch)
elif ch == ')':
while ops[-1] != '(':
postfix.append(ops.pop())
ops.pop()
elif ch in op:
if len(ops) == 0:
ops.append(ch)
elif ops[-1] != '(' and op[ops[-1]] >= op[ch]:
while ops and ops[-1] != '(' and op[ops[-1]] >= op[ch]:
postfix.append(ops.pop())
ops.append(ch)
else:
ops.append(ch)
while len(ops):
postfix.append(ops.pop())
return postfix
def inf2pre(s):
ss = ''
for i in range(len(s)-1,-1,-1):
if s[i] == '(':
ss += ')'
elif s[i] == ')':
ss += '('
else:
ss += s[i]
L = inf2post(ss)
return L[::-1]
infix = input('Enter an Infix Expression: ')
postfix = inf2post(infix)
print('Postfix:', end= ' ')
for ch in postfix:
print(ch, end='')
print()
prefix = inf2pre(infix)
print('Prefix:', end= ' ')
for ch in prefix:
print(ch, end='')
print()
Comments
Leave a comment