不畏惧

博客园 首页 新随笔 联系 订阅 管理

简单计算器的实现:

计算: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)

 

posted on 2017-05-04 17:01  不畏惧  阅读(107)  评论(0编辑  收藏  举报