将Infix转换为Postfix(堆栈)

时间:2020-05-04 09:05:46

标签: python stack postfix-mta infix-notation

如何使用堆栈执行以下操作来更改此infix-> postfix:

对待减号操作相反的符号“ ^”作为负号, 并且仅在后缀表示法中可用。此外,将其视为 数字而不是运算。

class Conversion:
    def __init__(self, capacity):
        self.top = -1
        self.capacity = capacity
        self.array = []
        self.output = []
        self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}

    def isEmpty(self):
        return True if self.top == -1 else False

    def peek(self):
        return self.array[-1]

    def pop(self):
        if not self.isEmpty():
            self.top -= 1
            return self.array.pop()
        else:
            return "$"

    def push(self, op):
        self.top += 1
        self.array.append(op)

    def isOperand(self, ch):
        return ch.isalpha()

    def notGreater(self, i):
        try:
            a = self.precedence[i]
            b = self.precedence[self.peek()]
            return True if a <= b else False
        except KeyError:
            return False

    def infixToPostfix(self, exp):

        for i in exp:
            if self.isOperand(i):
                self.output.append(i)

            elif i == '(':
                self.push(i)

            elif i == ')':
                while (not self.isEmpty()) and self.peek() != '(':
                    a = self.pop()
                    self.output.append(a)
                if not self.isEmpty() and self.peek() != '(':
                    return -1
                else:
                    self.pop()

            else:
                while not self.isEmpty() and self.notGreater(i):
                    self.output.append(self.pop())
                self.push(i)

        while not self.isEmpty():
            self.output.append(self.pop())

        print("".join(self.output))


exp = "(-a + b)"
obj = Conversion(len(exp))
obj.infixToPostfix(exp)
Current output: ab+-
Required output: ^ab+

Input/Output Examples

0 个答案:

没有答案
相关问题