使用正则表达式实现(加减乘除)计算器(python实现)

本文介绍了一种使用正则表达式和Python实现的数学表达式解析算法,该算法能够处理包含加减乘除及括号的复杂表达式,并通过逐步替换的方式计算出最终结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import re

#source为计算表达式字符串
source='((100-15*(10.2/2)))*10+(9+8/2*4)'

#判断字符串中无效字符函数
def check(s):
    flag=True
    if re.findall('[a-zA-Z]',s):
        print('Invalid')
        flag=False
    return  flag

#将表达式字符串中的空格,++等字符进行修正
def format(s):
    s=s.replace(' ','')
    s=s.replace('++','+')
    return s

#加法和减法函数
def cal_add_sub(s):
    while re.search('\d+\.?\d*[-+]\d+\.?\d*', s):
        print(s)
        ret = (re.search('\d+\.?\d*[-+]\d+\.?\d*', s)).group()
        x, y = re.split('[-+]', ret)
        x = float(x)
        y = float(y)
        if re.search('\+',ret):
            ret1 = x + y
            s = re.sub('\d+\.?\d*[-+]\d+\.?\d*', str(ret1), s, 1)
        elif re.search('\-',ret):
            ret1 = x - y
            s = re.sub('\d+\.?\d*[-+/]\d+\.?\d*', str(ret1), s, 1)
    else:
        z=re.search('\d+\.?\d*',s).group()
        return z
#乘法和除法函数
def  cal_mul_div(s):
    while re.search('\d+\.?\d*[*/]\d+\.?\d*',s):
        print(s)
        ret = (re.search('\d+\.?\d*[*/]\d+\.?\d*', s)).group()
        x,y=re.split('[*/]',ret)
        x=float(x)
        y=float(y)
        if re.search('\*',ret):
            ret1=x*y
            print(ret1)
            s = re.sub('\d+\.?\d*[*/]\d+\.?\d*', str(ret1), s, 1)
        elif re.search('/',ret):
            ret1=x/y
            print(ret1)
            s = re.sub('\d+\.?\d*[*/]\d+\.?\d*', str(ret1), s, 1)
    else:
        z=cal_add_sub(s)
        return z

#计算过程

if check(source):
    strs=format(source)
    while re.search('\(',strs):
        ret=re.search('\([^()]+\)',strs).group()
        ret=cal_mul_div(ret)
        strs=re.sub('\([^()]+\)',cal_mul_div(ret),strs,1)
    else:
        strs=cal_mul_div(strs)
        print(strs)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

往后余生MBSE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值