python 基础练习(五)---计算器

方法一:

#coding=utf-8
import re
from functools import reduce

def calcu(calculate):
    while True:
        match_list = re.findall(r'\([^()]+\)',calculate)
        if match_list:
            for item in match_list:
                match_result = cal(item)
                calculate = calculate.replace(item,str(match_result))
        else:
            cal(calculate)
            break
    return cal(calculate)

def cal(i):
    i=i.strip('(')
    i=i.strip(')')
    result_am=am_c(i)
    result=float(result_am)
    return result

def am_c(i):
    while True:
        if '+-' in i:
            i = i.replace('+-', '-')
        elif '--' in i:
            i = i.replace('--','+')
        elif '++' in i:
            i = i.replace('++','+')
        elif '-+' in i:
            i=i.replace('-+','-')
        else:
            break
    
    a_li=re.split(r'\+',i)
    y=0
    for a in a_li:
        if '-' in a:
            mi_li = re.split(r'-',a)
            if mi_li[0] == '':
                mi_li[1] = '-' + mi_li[1]
                mi_li.pop(0)
            for item in mi_li:
                if item.endswith('*') or item.endswith('/'):
                    s=mi_li.index(item)
                    mi_li[s]=mi_li[s] + '-' + mi_li[s+1]
                    mi_li.pop(s+1)
            x=0
            for b in mi_li:
                mi_li[x]=md_c(b)
                x+=1
            result_mi = reduce(lambda x,y:float(x)-float(y),mi_li)
            a_li[y] = result_mi
        else:
            a_li[y]=md_c(a)
        y+=1
    result_a = reduce(lambda x,y:float(x)+float(y),a_li)
    return result_a

def md_c(i):
    mu_li = re.split(r'\*',i)
    if mu_li[-1] == '':
        mu_li.pop(-1)
    z=0
    for c in mu_li:
        if '/' in c:
            d_li = re.split(r'/',c)
            result_d=reduce(lambda x,y:float(x)/float(y),d_li)
            mu_li[z]=result_d
        else:
            pass
        z+=1
    result_mu=reduce(lambda x,y:float(x)*float(y),mu_li)
    return result_mu

while True:
    in_calculate = input('请输入要计算的内容:')
    in_calculate = in_calculate.replace(' ','')
    if in_calculate == 'q' or in_calculate == 'Q':
        exit('程序退出')
    if len(in_calculate) == 0:
        continue
    if re.search(r'[^\d\-\/*+\(\)]',in_calculate) or '()' in in_calculate or in_calculate.count('(') != in_calculate.count(')'):
        print('输入错误,请重新输入')
        continue
    else:
        result = calcu(in_calculate)
        print('\033[34m 计算结果:%s\033[0m'%result)
        print('\033[35m 正确结果:%s\033[0m' % eval(in_calculate))

方法二:

#coding=utf-8
import re,sys
from functools import reduce

def compute_mul_div(mg):
    '''
    定义一个乘除函数
    :param mg:
    :return:
    '''
    num = mg[0]  #  -40/5
    match = re.search("\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*",num)
    if not match:
        return
    content = re.search('\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*',num).group()
    if len(content.split('*')) > 1:
        v1,v2 = content.split('*')
        value = float(v1) * float(v2)
        # print('v1>>>%s and v2>>>%s'%(str(v1),str(v2)))
        # print('computer_mul:%s and %s'% (str(content),str(value)))
    else:
        v1, v2 = content.split('/')
        value = float(v1) / float(v2)
        # print('v1>>>%s and v2>>>%s' % (str(v1), str(v2)))
        # print('computer_del:%s and %s' % (str(content),str(value)))
    pur,suf = re.split('\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*',num,1)
    new_str = '%s%s%s'%(pur,value,suf)
    mg[0] = new_str
    #print('pur>>>%s    value>>>%s     uer>>>%s   new_str>>>%s' % (pur, value,suf,new_str))
    compute_mul_div(mg)

def compute_add_sub(mg):
    '''
    运算表达式加减函数
    :param mg:
    :return:
    '''
    while True:
        if mg[0].__contains__('+-') or mg[0].__contains__('++') or mg[0].__contains__('-+') or mg[0].__contains__('--'):
            mg[0] = mg[0].replace('+-', '-')  # 将-替换掉+-
            mg[0] = mg[0].replace('++', '+')  # 将+替换掉++
            mg[0] = mg[0].replace('-+', '-')  # 将-替换掉-+
            mg[0] = mg[0].replace('--', '+')  # 将+替换掉--
        else:
            break
    if mg[0].startswith('-'):  # 如果arg的第0个元素是以-开头
        mg[1] += 1  # arg的第一个元素自加1
        mg[0] = mg[0].replace('-', '&')
        mg[0] = mg[0].replace('+', '-')
        mg[0] = mg[0].replace('&', '+')  # 将-变+,+变-
        mg[0] = mg[0][1:]  # 将arg中第0个元素中前面多出来的符号去掉
    num = mg[0]  # -40/5
    match = re.search('\d+\.*\d*[\+\-]{1}\d+\.*\d*',num)
    if not match:
        return
    content = re.search('\d+\.*\d*[\+\-]{1}\d+\.*\d*',num).group()
    if len(content.split('+')) > 1:
        v1, v2 = content.split('+')
        value = float(v1) + float(v2)
        # print('v1>>>%s and v2>>>%s' % (str(v1), str(v2)))
        # print('computer_add:%s and %s' % (str(content),str(value)))
    else:
        v1, v2 = content.split('-')
        value = float(v1) - float(v2)
        # print('v1>>>%s and v2>>>%s' % (str(v1), str(v2)))
        # print('computer_sub:%s and %s' % (str(content),str(value)))
    pur,suf = re.split('\d+\.*\d*[\+\-]{1}\d+\.*\d*',num,1)
    new_str = '%s%s%s'%(pur,value,suf)
    mg[0] = new_str
    compute_add_sub(mg)

def calate(match_group):
    '''
    计算表达式函数
    :param match_group:
    :return:
    '''
    mg = [match_group.strip('()'),0]   # mg = ['-40/5',0]
    print(mg)
    compute_mul_div(mg)     #调用乘除运算函数
    compute_add_sub(mg)     #调用加减运算函数
    if divmod(mg[1],2)[1] == 1:
        result = float(mg[0])
        result *= -1
        print('divmod_result:%s'%result)
    else:
        result = float(mg[0])
    print('in the calator-new_str():%s'%mg)
    return result

def kuohao(calculate):
    '''
    取出表达式中括号函数
    :param calculate:
    :return:
    '''
    while True:
        match = re.search('\([^()]+\)',calculate)   #使用正则表达式 取出优先级最高的括号 并计算
        if match:   #如果表达式中有括号
            match_group=match.group()
            match_result = calate(match_group)  #调用计算函数
            calculate = calculate.replace(match_group,str(match_result)) #将括号计算后的结果替换原参数
        else:   #若表达式中没有括号
            calate(calculate)
            break
    return calate(calculate)

print('\033[33m 欢迎使用计算器 :\033[0m'.center(50,'-'))
print('例:1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))')
while True:
    calculate_input=input('\033[32m请输入计算的表达式 | (退出:q)>>>\033[0m')
    calculate_input=calculate_input.replace(' ','')
    if calculate_input=='q':
        exit('程序退出')
    if len(calculate_input)==0:
        continue
    if re.search('[^\d\+\-\*/\(\)]',calculate_input):   #使用正则表达式判断用户输入是否是数字、"+-*/"、"()"
        print('\033[31m 输入错误,请重新输入!!!\033[0m')
    else:
        result = kuohao(calculate_input)    #调用去除括号的函数
        print('\033[34m 计算结果>>>%s\033[0m'%result)
        print('\033[35m 正确结果>>>%s\033[0m' % eval(calculate_input))

其实eval()就可以

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值