6. Prefix to Infix expression
In [1]:
Copied!
expression = "* + a b / e f"
expression = expression.split()
expression = "* + a b / e f"
expression = expression.split()
In [2]:
Copied!
def prefix_to_infix(expression):
operator = ["+", "-", "*", "/", "^"]
stack = []
expression = expression[::-1]
for i in expression:
if i in operator:
if len(stack) > 0:
a = stack.pop()
b = stack.pop()
exp = a + i + b
stack.append(exp)
else:
stack.append(i)
return stack[-1]
def prefix_to_infix(expression):
operator = ["+", "-", "*", "/", "^"]
stack = []
expression = expression[::-1]
for i in expression:
if i in operator:
if len(stack) > 0:
a = stack.pop()
b = stack.pop()
exp = a + i + b
stack.append(exp)
else:
stack.append(i)
return stack[-1]
In [3]:
Copied!
prefix_to_infix(expression)
prefix_to_infix(expression)
Out[3]:
'a+b*e/f'
In [ ]:
Copied!