zoukankan      html  css  js  c++  java
  • 四则运算表达式二叉树法求后缀表达式

    data = """
    3+51*4-23/(3+8)-5
    (42+33*(2+5))-7*8
    """
    
    nex = []  # 存储括号对应关系
    token = []
    
    
    # 预处理
    def pre(s):
        global token
        global nex
        token = []
        nex = []
        stack = []
        i = 0
        while i < len(s):
            if s[i] == '(':
                token.append("(")
                i += 1
            elif s[i] == ')':
                token.append(")")
                i += 1
            elif s[i] in "+-*/":
                token.append(s[i])
                i += 1
            elif s[i].isspace():
                i += 1
            else:
                v = ""
                while i < len(s) and s[i].isdigit():
                    v += s[i]
                    i += 1
                token.append(v)
        i = 0
        nex = [0] * len(token)
        while i < len(token):
            if token[i] == "(":
                stack.append(i)
                i += 1
            elif token[i] == ")":
                x = stack.pop()
                nex[i] = x
                nex[x] = i
                i += 1
            else:
                i += 1
    
    
    # 运算符优先级
    def priority(op):
        return {"+": 0, "-": 0, "*": 1, "/": 1}[op]
    
    
    # 计算值
    def cal(x, y, op):
        if op == "+":
            return x + y
        elif op == "-":
            return x - y
        elif op == "*":
            return x * y
        else:
            return x / y
    
    
    # 将token[f:t]转换成结点
    def node(token, f, t):
        r = {}
        minOp = -1
        minOpPriority = 0xfffffff
        while token[f] == "(" and token[t] == ")":
            f += 1
            t -= 1
        if f == t:
            r["value"] = int(token[f])
            return r
        i = f
        while i <= t:
            if token[i] == '(':
                i = nex[i] + 1
            elif token[i] in "+-*/":
                op = priority(token[i])
                if op <= minOpPriority:
                    minOp = i
                    minOpPriority = op
                i += 1
            else:
                i += 1
        r["left"] = node(token, f, minOp - 1)
        r["right"] = node(token, minOp + 1, t)
        r["op"] = token[minOp]
        r["value"] = cal(r["left"]["value"], r["right"]["value"], r["op"])
        return r
    
    
    # 打印后序
    def houxu(node):
        if not "op" in node:
            return [node["value"]]
        l = houxu(node["left"])
        r = houxu(node["right"])
        op = node["op"]
        return l + r + [op]
    
    
    def main(s):
        s = s.strip()
        pre(s)
        n = node(token, 0, len(token) - 1)
        print(houxu(n))
        return n["value"]
    
    
    for i in data.split():
        print(i, "=", eval(i), main(i))
    
    
  • 相关阅读:
    iOS多线程与网络开发之NSURLCache
    NEFU 117-素数个数的位数(素数定理)
    UISegmentedControl 的使用
    C++使用ADO存取图片
    王立平-- Swift
    浮生猫绘——落入平一的精灵
    BZOJ 1692: [Usaco2007 Dec]队列变换 [后缀数组 贪心]
    POJ2774 Long Long Message [后缀数组]
    BZOJ 2119: 股市的预测 [后缀数组 ST表]
    BZOJ 1717: [Usaco2006 Dec]Milk Patterns 产奶的模式 [后缀数组]
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/6395429.html
Copyright © 2011-2022 走看看