计算器 随机红包

def atom_cal(exp):
    if "*"in exp:
        a, b = exp.split("*")
        return str(float(a)*float(b))
    elif "/" in exp:
        a, b = exp.split("/")
        return str(float(a)/float(b))
def mul_div(exp):  # 先匹配乘除
    while True:
        ret = re.search("d+[/*]-?d+", exp)
        if ret:
            chengchu = ret.group()  # 1*-22
            res = atom_cal(chengchu)
            exp = exp.replace(chengchu, res)
        else:return exp
def func(exp):
    exp = exp.replace("--","+")
    exp = exp.replace('+-','-')
    exp = exp.replace('-+','-')
    exp = exp.replace('++','+')
    return exp
def add_sub(exp):
    ret = re.findall('[+-]?d+(?:.d+)?', exp)
    s_um = 0
    for i in ret:
        s_um+=float(i)
    return s_um
def main(exp):
    exp = mul_div(exp)
    exp = func(exp)
    print(exp)
    exp = add_sub(exp)
    print(exp)
main('2-1*-22-3-4/-5')
import re
def atom_cal(exp):# 计算乘除的函数
    if '*' in exp:
        a,b = exp.split('*')
        return str(float(a) * float(b))
    elif '/' in exp:
        a, b = exp.split('/')
        return str(float(a) / float(b))

def format_exp(exp):
    exp = exp.replace('--','+')
    exp = exp.replace('+-','-')
    exp = exp.replace('-+','-')
    exp = exp.replace('++','+')
    return exp

def mul_div(exp):
    while True:
        ret = re.search('d+(.d+)?[*/]-?d+(.d+)?', exp) # 匹配括号里的乘除
        if ret:#如果匹配到乘除的话
            atom_exp = ret.group()#拿到匹配的结果
            res = atom_cal(atom_exp)# 执行计算乘除的函数,并且拿到返回值
            exp = exp.replace(atom_exp,res)#将拿到的计算结果替换以前得
        else:return exp# 匹配完以后返回结果
def add_sub(exp):
    ret = re.findall('[+-]?d+(?:.d+)?', exp)# 匹配到有加减的内容,这里需要用取消分组操作
    exp_sum = 0
    for i in ret:
        exp_sum += float(i)
    return exp_sum

def cal(exp):
    exp = mul_div(exp)# 执行乘除函数
    exp = format_exp(exp)# 拿到计算 完乘除的结果,转换成小数
    exp_sum = add_sub(exp)# 将计算完乘除的结果传递到匹配加减的函数中,并且拿到匹配的内容
    return exp_sum   # float

def main(exp):# 1
    exp = exp.replace(' ','')# 2去除空格
    while True:# 因为需要不断拿括号里的内容
        ret = re.search('([^()]+)', exp)# 匹配到最内层括号
        if ret :# 如果匹配到结果
            inner_bracket = ret.group()#拿到匹配内容
            res = str(cal(inner_bracket))#执行cal()函数  并且拿到计算加减的结果
            exp = exp.replace(inner_bracket, res)# 然后将计算的结果替换掉匹配掉以前得结果
            exp = format_exp(exp) # 处理加减号
        else:break # 匹配不到就结束
    return cal(exp)
s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
ret = main(s)
print(ret, type(ret))

 

随机红包 
import random def red_packet(money,nub): money = money * 100 ret = random.sample(range(1, money), nub-1) ret.sort() ret.insert(0, 0) ret.append(money) print(ret) for i in range(len(ret)-1): yield (ret[i+1]-ret[i])/100 ret_g = red_packet(100,5) print(ret_g) for c in ret_g: print(c)

  

原文地址:https://www.cnblogs.com/y122988/p/9520457.html