Please provide the code below. And also give the procedure in a table form.
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)
2. a/b^c^d+(e+f)/g^h-i*j/(k*l*'m^n)
class Stack:
def __init__(self):
self.stack = []
def isEmpty(self):
return self.stack == []
def push(self, obj):
self.stack.append(obj)
def pop(self):
return self.stack.pop()
def peek(self):
return self.stack[-1]
def infixToPostfix(s):
priority = {'(': 1, '-': 2, '+': 2, '/': 3, '*': 3, '^': 4}
opstack = Stack()
output = []
for token in s:
if token.isalpha():
output.append(token)
elif token == '(':
opstack.push(token)
elif token == ')':
top_token = opstack.pop()
while top_token != '(':
output.append(top_token)
top_token = opstack.pop()
elif token in priority.keys():
while (not opstack.isEmpty()) and (priority[opstack.peek()] >= priority[token]):
output.append(opstack.pop())
opstack.push(token)
while not opstack.isEmpty():
output.append(opstack.pop())
return output
def infixToPrefix(s):
priority = {')': 1, '-': 2, '+': 2, '/': 3, '*': 3, '^': 4}
opstack = Stack()
output = []
for token in s[::-1]:
if token.isalpha():
output.append(token)
elif token == ')':
opstack.push(token)
elif token == '(':
top_token = opstack.pop()
while top_token != ')':
output.append(top_token)
top_token = opstack.pop()
elif token in priority.keys():
while (not opstack.isEmpty()) and (priority[opstack.peek()] >= priority[token]):
output.append(opstack.pop())
opstack.push(token)
while not opstack.isEmpty():
output.append(opstack.pop())
return output[::-1]
test = ['a^b/c+d-(e/f-g+(h+i-j)^k+l-m/n)', 'a/b^c^d+(e+f)/g^h-i*j/(k*l*m^n)']
for c in test:
print('Infix: ', c, 'Postfix: ', ''.join(infixToPostfix(c)))
print('Infix: ', c, 'Prefix: ', ''.join(infixToPrefix(c)))
Comments
Leave a comment