zoukankan      html  css  js  c++  java
  • python 练习3

    简单计算器的实现:

    计算:1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'

    #!usr/bin/env python
    # encoding: utf-8
    import re
    
    #乘除运算
    def chengchu(formula):
        while True:
            s_formula = re.search('d+.?d*[*/][-]?d+.?d*',formula)
            if s_formula:
                s_formula_list = re.split('[*/]',s_formula.group())
                if '*' in s_formula.group():
                    s_sub = float(s_formula_list[0]) * float(s_formula_list[1])
                    formula = formula.replace(s_formula.group(),str(s_sub))
                elif '/' in s_formula.group():
                    s_sub = float(s_formula_list[0]) / float(s_formula_list[1])
                    formula = formula.replace(s_formula.group(),str(s_sub))
            else:
                print(s_formula_list,formula)
                res = jiajian(formula)
                return res
    
    
    #加减运算
    def jiajian(formula2):
        if '+-' in formula2 or '++' in formula2 or '-+' in formula2 or '--' in formula2:
            formula2 = formula2.replace('+-', '-')
            formula2 = formula2.replace('++', '+')
            formula2 = formula2.replace('-+', '-')
            formula2 = formula2.replace('--', '+')
        while True:
            s_f = re.search('d+.?d*[+-]d+.?d*',formula2)
            if s_f:
                s_f_list = re.split('[+-]',s_f.group())
                print(s_f_list)
                if '-' in s_f.group():
                    s_f_sub = float(s_f_list[0]) - float(s_f_list[1])
                    formula2 = formula2.replace(s_f.group(),str(s_f_sub))
                elif '+'in s_f.group():
                    s_f_sub = float(s_f_list[0]) + float(s_f_list[1])
                    formula2 = formula2.replace(s_f.group(), str(s_f_sub))
                continue
            else:
                print(formula2)
            return formula2
    
    
    
    #开始运算
    def calc(arg):
        while True:
            m = re.search("([^()]+)",arg)
            if m:
                formula = m.group().strip('()')
                print(formula)
                m_result = chengchu(formula)
                arg = arg.replace(m.group(),str(m_result))
                continue
            else:
                print(arg)
                su = chengchu(arg)
                print(su)
                break
    
    if __name__ == "__main__":
        a = '1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
        # a = '1-2*-1388338.2476190478'
        calc(a)
  • 相关阅读:
    从搭eclipse环境到导入maven工程
    基于jquery的多选下拉列框再次更改样式和交互
    BootStrap的typeahead使用过程中遇到的问题
    Vue webapp项目通过HBulider打包原生APP
    微信相机
    前端小新手,记录项目中不懂的问题
    判断pdf、word文档、图片等文件类型(格式)、大小的简便方法
    JavaScript学习笔记(一)——Map、Set与iterable
    oracle nvl函数
    mybaits中主键自动生成并返回主键
  • 原文地址:https://www.cnblogs.com/cloud-80808174-sea/p/6808132.html
Copyright © 2011-2022 走看看