zoukankan      html  css  js  c++  java
  • Python第五天-简易计算器

    使用python实现简易计算器-支持加减乘除和括号

    priority_dict = {  # 操作符优先级字典
        "+": 1,
        "-": 1,
        "*": 2,
        "/": 2
    }
    
    operands_dict = {  # 操作符函数字典
        "+": lambda x, y: x + y,
        "-": lambda x, y: x - y,
        "*": lambda x, y: x * y,
        "/": lambda x, y: x / y,
    }
    
    
    def calculator(expression):
        suffix = _infix2suffix(expression)
        return _calsuffix(suffix)
    
    
    def _calsuffix(suffix):
        '''
        计算后缀表达式
        :param suffix: 后缀表达式
        :return:
        '''
        stack = []
        for item in list(suffix):
            '''
            是数字,入栈
            是操作符,出栈2个,计算,入栈
            '''
            if item.isdecimal():
                stack.append(item)
            elif item in operands_dict.keys():
                num2 = float(stack.pop())
                num1 = float(stack.pop())
                stack.append(operands_dict[item](num1, num2))
            else:
                raise KeyError("illegal expression")
        if len(stack) != 1:
            raise KeyError("illegal expression")
        return stack.pop()
    
    
    def _infix2suffix(expression):
        '''
        中缀表达式转后缀表达式
        :param expression: 中缀表达式
        :return: 后缀表达式
        '''
        result = []  # 结果列表
        stack = []  # 栈
        for item in expression:
            '''
            是数字,直接添加到结果列表
            是左括号,入栈
            是右括号,依次出栈,直到左括号
            是操作符,栈为空或栈顶为左括号或当前操作符比栈顶操作符优先级高,直接入栈
                    其他情况,依次出栈,直到栈为空或栈顶为左括号或当前操作符比栈顶操作符优先级高,当前操作符入栈
            '''
            if item.isdecimal():
                result.append(item)
            else:
                if item == "(":
                    stack.append(item)
                elif item == ")":
                    while True:
                        if len(stack) == 0:
                            raise KeyError("illegal expression")
                        pop_item = stack.pop()
                        if pop_item == "(":
                            break
                        result.append(pop_item)
                elif item in priority_dict.keys():
                    if len(stack) == 0 or 
                            stack[len(stack) - 1] == "(" or 
                            priority_dict[item] > priority_dict[stack[len(stack) - 1]]:
                        stack.append(item)
                    else:
                        while True:
                            if len(stack) == 0 or 
                                    stack[len(stack) - 1] == "(" or 
                                    priority_dict[item] > priority_dict[stack[len(stack) - 1]]:
                                break
                            result.append(stack.pop())
                        stack.append(item)
                else:
                    raise KeyError("illegal expression")
        while len(stack) > 0:
            result.append(stack.pop())
        return "".join(result)
    
    if __name__ == "__main__":
        print(calculator("1+2/(3*3-5)*3"))  # 1233*5-/3*+
    
  • 相关阅读:
    POJ 1775 (ZOJ 2358) Sum of Factorials
    POJ 1844 Sum
    HDOJ 1081(ZOJ 1074) To The Max(动态规划)
    HDOJ 2012 素数判定
    HDOJ 2011 多项式求和
    HDOJ 2010 水仙花数
    马云最新发言:让员工、客户、合作伙伴比自己更强
    乐视手机1S正式发售,乐视商城官网抽风遭网友吐槽
    C++引用(Reference)
    实验三 二叉树的基本操作(建立)及遍历
  • 原文地址:https://www.cnblogs.com/strongmore/p/13593695.html
Copyright © 2011-2022 走看看