Answer to Question #201513 in Python for mahikah

Question #201513

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)


1
Expert's answer
2021-06-01T03:04:02-0400
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)))

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