DeTechn Blog

Python解析 算数表达式求值 栈的使用

使用Python实现一种算数表达式求值的算法,模拟这种使用栈的方式,这是由E.W.Dijkstra在20世纪60年代发明的一种非常简单的算法。代码模拟仅仅表现一种编程思想,代码的逻辑并不完全

if __name__ == "__main__":
    cal_str = input("请输入算数表达式(e.g.(((1+2)*(3+5))+2), 只适合简单的算数表达式):")
    num_stack = []
    symbol_stack = []
    for chr in cal_str:
        #print(chr)
        if chr == "(":
            continue
        elif chr == "" or chr == "\t" or chr == "\n":
            continue
        elif chr == "+":
            symbol_stack.append(chr)
        elif chr == "-":
            symbol_stack.append(chr)
        elif chr == "*":
            symbol_stack.append(chr)
        elif chr == "/":
            symbol_stack.append(chr)
        elif chr == "sqrt":
            symbol_stack.append(chr)
        elif chr == ")":
            total_num = num_stack.pop()
            now_symbol = symbol_stack.pop()
            if now_symbol == "+":
                total_num += num_stack.pop()
            if now_symbol == "-":
                total_num -= num_stack.pop()
            if now_symbol == "*":
                total_num *= num_stack.pop()
            if now_symbol == "/":
                total_num /= num_stack.pop()
            num_stack.append(total_num)
        else:
            num_stack.append(int(chr))
    print(num_stack.pop())

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »