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*+
    
  • 相关阅读:
    背景大图隔几秒切换(非轮播,淡入淡出)--变形金刚joy007 项目总结
    call(京基填小票拍照片)
    加载图片、倒计时--Columbia项目总结
    kellogg项目总结
    js 跨域
    js 继承inheritance/extends
    一号店分享会
    日历,类似旅行网站的酒店入住
    js 数组的判断
    Building a Non-blocking TCP server using OTP principles
  • 原文地址:https://www.cnblogs.com/strongmore/p/13593695.html
Copyright © 2011-2022 走看看