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*+
    
  • 相关阅读:
    [转] 英语飙升的好方法
    jndi数据源方式配制SPY
    OJB查询
    ODP.NET应用之我所见
    C#中利用ODP实现瞬间导入百万级数据详解
    Sys.Extended.UI' is null or not an object 中文的訊息
    oracle数据库连接字符串
    seo
    宽幅FLASH产品展示代码多图带左右显示按钮 图
    网站盈利模式分类详解
  • 原文地址:https://www.cnblogs.com/strongmore/p/13593695.html
Copyright © 2011-2022 走看看