计算器

#!/usr/bin/env python
#-*-coding=utf-8 -*-
#GKX
import re

def dealwith(express):
    '''
    将表达式中 ‘+-’替换为 -   --替换为+
    :param new_express: 计算完原子型表达式后的主表达式
    :return:
    '''
    express:express = express.replace('+-','-')
    express:express = express.replace('--','+')
    return express

def cal_exp_son(exp_son):
    '''
    计算原子型表达式 两个数之间的乘除法
    :param exp_son: 传进来的,只有两个数之间的乘除法
    :return: 返回计算后的值
    '''
    if '/' in exp_son:
        a,b = exp_son.split('/')  # -40/5
        return str(float(a)/float(b))
    elif '*' in exp_son:
        a,b = exp_son.split('*')
        return str(float(a)* float(b))


def cal_express_no_bracket(exp):
    '''
    计算里层不带括号的表达式
    :param exp: 最里层不带括号的表达式传进来
    :return:
    '''
    exp = exp.strip('()')
    #先乘除后加减
    #-40/5*8+2         9-2*5/3+7/3*99/4*2998+10*568/14
    while True:
        ret = re.search('\d+\.?\d*[*/]-?\d+\.?\d*',exp)
        if ret:
            exp_son = ret.group() #子表达式  最简单的乘除法
            ret = cal_exp_son(exp_son)
            exp = exp.replace(exp_son,ret)   #ret为计算后的值,替换为 乘除的式子
            #111print(exp)
            exp = dealwith(exp)
            #111print(exp)
        else:  #当表达式里没有了乘除法
            ret = re.findall('-?\d+\.?\d*',exp)
            sum = 0
            for i in ret:
                sum += float(i)
            return str(sum)


#提取括号里面没有其他括号的表达式
def remove_bracket(new_express):
    while True:
        ret = re.search('\([^()]+\)',new_express)
        if ret:
            express_no_bracket = ret.group()
            #111print('匹配到内部不再有括号的值',express_no_bracket)   #表达式没括号
            ret = cal_express_no_bracket(express_no_bracket)
            #print(new_express,express_no_bracket,ret)
            new_express = new_express.replace(express_no_bracket,ret)
            #print(new_express)
            #new_express = dealwith(new_express)
            #111print(new_express)
        else:
            #111print('表达式中没有括号了',new_express)
            ret = cal_express_no_bracket(new_express)
            #111print(ret)
            return ret

#去空格
def calculator(express):
    #express = input('表达式')
    if express.count('(') != express.count(')'):
        print('表达式括号有误,请检查并重新输入')
    else:
        new_express = re.sub('[\s]','',express) #express.replace(' ','')
        #11print(new_express)
        res = remove_bracket(new_express)
        print(res)

express = '1 - 2 * ( ( (6 0) -3 0  +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
calculator(express)

 

import re
def math(dic):
    x,y=float(dic['x']),float(dic['y'])
    if dic['mark']=='+':return x+y
    elif dic['mark']=='-':return x-y
    elif dic['mark']=='*':return x*y
    else:return x/y
def suansu(re_str):
    ret4=re.search(r'(?P<x>\d+\.?\d*)(?P<mark>[*/])(?P<y>[\-]?\d+\.?\d*)',re_str)
    try:
        while ret4.group():
            re_str=re_str.replace(ret4.group(),str(math(ret4.groupdict())))
            if '--' in re_str: re_str =re_str.replace('--','+')
            if '++' in re_str: re_str =re_str.replace('++','+')
            ret4=re.search(r'(?P<x>\d+\.?\d*)(?P<mark>[*/])(?P<y>[\-]?\d+\.?\d*)',re_str)
    except AttributeError:pass
    ret4=re.search(r'(?P<x>\d+\.?\d*)(?P<mark>[+\-])(?P<y>[\-]?\d+\.?\d*)',re_str)
    try:
        while ret4.group():
            re_str=re_str.replace(ret4.group(), str(math(ret4.groupdict())))
            ret4=re.search(r'(?P<x>\d+\.?\d*)(?P<mark>[+\-])(?P<y>[\-]?\d+\.?\d*)',re_str)
    except AttributeError:return re_str
def main(user_inp):
    while True:
        if not re.search('\([+*/\d.\-]*\)',user_inp):
            print(user_inp)
            return suansu(user_inp)
        else:
            for i in re.findall('\([+*/\d.\-]*\)',user_inp):
                user_inp=user_inp.replace(i,suansu(i.replace('(','').replace(')','')))
                print (user_inp)
a='1 - 2 * ( ( (6 0) -3 0  +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
print(main(a.replace(' ','')))

 

posted @ 2018-12-10 17:52  扫驴  阅读(240)  评论(0编辑  收藏  举报