python中缀表达式变后缀表达式


def string_reverse(string):
      def icp(s):#定义优先级(栈外)
        if s == "#":
            return 0
        if s == "(":
            return 6
        if s == "*" or "/" or "%":
            return 4
        if s == "+" or "-":
            return 2
        if s == ")":
            return 1

    def isp(s):#定义栈内优先级
        if s == "#":
            return 0
        if s == "(":
            return 1
        if s == "*" or "/" or "%":
            return 5
        if s == "+" or "-":
            return 3
        if s == ")":
            return 6

    s2 = LinkedStack()
    tokens = string.split()
    string_2 = []
    s2.push("#")
    for ch in tokens:
        if ch.isdigit():#是数字就加到string_2中
            string_2.append(ch)
        else:
            while True:
                if icp(ch) > isp(s2.gettop()):
                    s2.push(ch)
                    break
                elif icp(ch) < isp(s2.gettop()):
                    x = s2.pop()
                    string_2.append(x)
                    break
                elif icp(ch) == isp(s2.gettop()):
                    y = s2.pop()
                    if y == '(':
                        break
                    else:
                        s2.pop()

    return string_2

def string_reverse(string):
    def icp(s):
        if s == "#":
            return 0
        if s == "(":
            return 6
        if s == "*" or "/" or "%":
            return 4
        if s == "+" or "-":
            return 2
        if s == ")":
            return 1

    def isp(s):
        if s == "#":
            return 0
        if s == "(":
            return 1
        if s == "*" or "/" or "%":
            return 5
        if s == "+" or "-":
            return 3
        if s == ")":
            return 6

    s2 = LinkedStack()
    tokens = string.split()
    string_2 = []
    s2.push("#")
    for ch in tokens:
        if ch.isdigit():
            string_2.append(ch)
        else:
            while True:
                if icp(ch) > isp(s2.gettop()):
                    s2.push(ch)
                    break
                elif icp(ch) < isp(s2.gettop()):
                    x = s2.pop()
                    string_2.append(x)
                    break
                elif icp(ch) == isp(s2.gettop()):
                    y = s2.pop()
                    if y == '(':
                        break
                    else:
                        s2.pop()

    return string_2

def main():
    string = "9 + ( 3 - 1 ) * 3 + 10 / 2 #"
    string_suf = string_reverse(string)
    print("后缀表达式为")
    print(string_suf)


if __name__ == "__main__":  # 定义程序入口
    main()

利用python的链栈实现中缀表达式转后缀表达式中间总是遗漏掉加号
刚学python,脑子里全是C语言,不知道究竟错哪了,哪位兄台help me

img