zoukankan      html  css  js  c++  java
  • 计算器作业

    1.对下列的字符串进行运算

    用到的知识点:

    正则表达式、函数、循环

    做题思路:

    1.做原子乘除运算
    2.筛选出原子公式,计算替换结果
    3.3.格式化多余+-符号,匹配:+1 -2这样的数(做累加)
    4.创建一个调用1 2 3的函数
    5.去掉多余空格,匹配()内只有公式的公式,计算替换计算结果

    s = '1 - 2 * ((60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2))'
    

    2.实现代码

    点击查看详细内容
      
    #2.计算器
    import re
    

    1.

    def atom_cal(exp): # 原子性操作:56 不能再拆了
    '''
    计算原子公式乘除法
    :param exp:cal函数筛选出的值
    :return:以字符串的形式,返回计算结果
    '''
    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))

    2.

    def mul_div(exp):
    '''
    筛选出原子公式,交给atom_cal函数计算
    :param exp: 原字符串公式
    :return:
    '''
    while 1:
    ret = re.search('d+(.d+)?[*/]-?d+(.d+)?',exp)
    if ret:
    atom_exp = ret.group()
    atom_ret = atom_cal(atom_exp)
    exp = exp.replace(atom_exp,atom_ret) # 计算结果替换原子公式
    else:return exp

    3.

    def format_exp(exp):
    '''
    格式化:把字符串2个加减变成1个
    :param exp:cal函数原子计算后的公式
    :return:格式化都的公式
    '''
    exp = exp.replace('--','+')
    exp = exp.replace('+-', '-')
    exp = exp.replace('++', '+')
    exp = exp.replace('-+', '-')
    return exp

    4.

    def add_sub(exp):
    ret = re.findall('[+-]?d+(?:.d+)?',exp)
    #print(ret) #匹配数字和符号+数字
    exp_sum = 0
    for i in ret:
    exp_sum += float(i)
    return exp_sum

    5.

    计算,做原子乘除、格式化+-符号、最后+-运算

    def cal(exp):
    exp = mul_div(exp)
    exp = format_exp(exp)
    return add_sub(exp)

    6.

    最后去空格,匹配括号内的表达式

    def r_strip(exp):
    exp = exp.replace(" ","") #去空格
    while 1:
    ret = re.search('([^()]+)',exp) #匹配()内是非()的任意长度字符
    if ret:
    cal_exp = ret.group()
    res = str(cal(cal_exp))
    exp = exp.replace(cal_exp,res)
    else:
    return cal(exp)

    ret = cal('2-1*-22-3-4/-5')

    print(ret)

    print(2+22.0-3+0.8)

    s = '1 - 2 * ((60-30 +(-40/5) * (9-25/3 + 7 /399/42998 +10 * 568/14 )) - (-43)/ (16-3*2))'
    ret = r_strip(s)
    print(ret)
    print(eval(s))

  • 相关阅读:
    【模板】Sparse-Table
    UVa 11235 Frequent values
    【模板】树状数组
    UVa 1428 Ping pong
    数学技巧
    UVa 11300 Spreading the Wealth
    UVa 11729 Commando War
    UVa 11292 Dragon of Loowater
    POJ 3627 Bookshelf
    POJ 1056 IMMEDIATE DECODABILITY
  • 原文地址:https://www.cnblogs.com/byho/p/10762087.html
Copyright © 2011-2022 走看看