Calculators code implementation - a reference to the

"""
该计算器思路:
     1、递归寻找表达式中只含有 数字和运算符的表达式,并计算结果
     2、由于整数计算会忽略小数,所有的数字都认为是浮点型操作,以此来保留小数
使用技术:
     1、正则表达式
     2、递归
 
执行流程如下:
******************** 请计算表达式: 1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) ) ********************
before: ['1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
-40.0/5=-8.0
after: ['1-2*((60-30+-8.0*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
========== 上一次计算结束 ==========
before: ['1-2*((60-30+-8.0*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
9-2*5/3+7/3*99/4*2998+10*568/14=173545.880953
after: ['1-2*((60-30+-8.0*173545.880953)-(-4*3)/(16-3*2))']
========== 上一次计算结束 ==========
before: ['1-2*((60-30+-8.0*173545.880953)-(-4*3)/(16-3*2))']
60-30+-8.0*173545.880953=-1388337.04762
after: ['1-2*(-1388337.04762-(-4*3)/(16-3*2))']
========== 上一次计算结束 ==========
before: ['1-2*(-1388337.04762-(-4*3)/(16-3*2))']
-4*3=-12.0
after: ['1-2*(-1388337.04762--12.0/(16-3*2))']
========== 上一次计算结束 ==========
before: ['1-2*(-1388337.04762--12.0/(16-3*2))']
16-3*2=10.0
after: ['1-2*(-1388337.04762--12.0/10.0)']
========== 上一次计算结束 ==========
before: ['1-2*(-1388337.04762--12.0/10.0)']
-1388337.04762--12.0/10.0=-1388335.84762
after: ['1-2*-1388335.84762']
========== 上一次计算结束 ==========
我的计算结果: 2776672.69524
"""

Calculator Code:

import re
 
 
DEF compute_mul_div (Arg):
     "" " Operation multiplication and division
    : Param expression: expression
    : Return: the results
    """
 
    selection = arg [0]
    mch = re.search('\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', val)
    if not mch:
        return
    content = re.search('\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', val).group()
 
    if len(content.split('*'))>1:
        n1, n2 = content.split('*')
        value = float(n1) * float(n2)
    else:
        n1, n2 = content.split('/')
        value = float(n1) / float(n2)
 
    before, after = re.split('\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', val, 1)
    new_str = "%s%s%s" % (before,value,after)
    arg [0] = new_str
    compute_mul_div (arg)
 
 
DEF compute_add_sub (Arg):
     "" " Operation subtraction
    : Param expression: expression
    : Return: the results
    """
    while True:
        if arg[0].__contains__('+-') or arg[0].__contains__("++") or arg[0].__contains__('-+') or arg[0].__contains__("--"):
            arg[0] = arg[0].replace('+-','-')
            arg[0] = arg[0].replace('++','+')
            arg[0] = arg[0].replace('-+','-')
            arg[0] = arg[0].replace('--','+')
        else:
            break
 
    if arg[0].startswith('-'):
        arg[1] += 1
        arg[0] = arg[0].replace('-','&')
        arg[0] = arg[0].replace('+','-')
        arg[0] = arg[0].replace('&','+')
        arg [0] = arg [0] [1 :]
    selection = arg [0]
    mch = re.search('\d+\.*\d*[\+\-]{1}\d+\.*\d*', val)
    if not mch:
        return
    content = re.search('\d+\.*\d*[\+\-]{1}\d+\.*\d*', val).group()
    if len(content.split('+'))>1:
        n1, n2 = content.split('+')
        value = float(n1) + float(n2)
    else:
        n1, n2 = content.split('-')
        value = float(n1) - float(n2)
 
    before, after = re.split('\d+\.*\d*[\+\-]{1}\d+\.*\d*', val, 1)
    new_str = "%s%s%s" % (before,value,after)
    arg [0] = new_str
    compute_add_sub(arg)
 
 
DEF Compute (expression The):
     "" " Operation Math
    : Param expression: expression
    : Return: the results
    """
    inp = [expression,0]
 
    # Processing multiplication and division expressions 
    compute_mul_div (inp)
 
    # 处理
    compute_add_sub(inp)
    if divmod(inp[1],2)[1] == 1:
        result = float(inp[0])
        result = result * -1
    else:
        result = float(inp[0])
    return result
 
 
DEF exec_bracket (expression The):
     "" " recursive processing bracket, and calculates
    : Param expression: expression
    : Return: final results
    "" " 
    # If the expression has no brackets, responsible for calculating the direct call function, the expression returns the results, such as: 2 * 1-82 + 444 
    IF  not re.search ( ' \ (([\ + \ - . \ * \ /] * \ + D \ * \ D *) 2 {,} \) ' , expression The):
        Final = Compute (expression The)
         return Final
     # Get the first bracket contains only a digital / decimal and operators 
    # as: 
    #     [ '1-2 * ((+ 60-30 (- 40.0 / 5) * (9-2 5 * / 7 + 3/99 * 3/10 * 4 * 2998 + 568/14)) - (- 4 * 3) / (16-3 * 2)) '] 
    #     identify: (- 40.0 / 5) 
    = the re.search Content ( ' \ (([\ + \ - \ * \ /]. * \ + D \ * \ D *) 2 {,} \) ' , expression The) .group ()
 
    # Split the expression, namely: 
    # The [ '1-2 * ((+ 60-30 (- 40.0 / 5) * (9-2 * 5/3 + 7/3 * 99/10 * 4 * 2998 + 568 / 14)) - (- 4 * 3) / (16-3 * 2)) '] 
    # divided further into three parts: [' 1-2 * ((+ 60-30 ((-40.0 / 5) * (9 . 5 * -2 / +. 3. 7 /. 3 * 99/10 *. 4 * 2998 + 568/14)) - (-. 4. 3 *) / (16-3 * 2)) '] 
    before, Nothing, After Re =. Split ( ' \ (([\ + \ - \ * \ /]. * \ + D \ * \ D *) 2 {,} \) ' , expression The,. 1 )
 
    print 'before:',expression
    content = content[1:len(content)-1]
 
    # Computed, extracted representation (-40.0 / 5), and viable results, namely: -40.0 / 5 = -8.0 
    RET = Compute (Content)
 
    print '%s=%s' %( content, ret)
 
    # Execution result splicing, [ '1-2 * ((+ 60-30 (-8.0 * (9-2 * 5/3 + 7/3 * 99/10 * 4 * 2998 + 568/14)) - ( *. 3 -4) / (16-3 * 2)) '] 
    expression the = " % S% S% S " % (before, RET, After)
     Print  ' After: ' , expression the
     Print  " = " * 10, ' the calculation end time " , " = " * 10
 
    # Looping continues parentheses next processing operation, this is an expression of the carriers have been processed, namely: 
    # [ '1-2 * ((+ -8.0 * 60-30 (5 * 9-2 / 3 + 7/99 * 3/10 * 4 * 2998 + 568/14)) - (- 4 * 3) / (16-3 * 2)) ']
 
    # So the cycle of operation until the brackets no longer contains the expression 
    return exec_bracket (expression The)
 
 
 
# Use __name__ purpose: 
#    Only executed python index.py, the following code was executed 
#    if the other person to import the module, the following code does not perform 
IF  __name__ == " __main__ " :
     # Print '*' * 20, "please calculation expression: "" 1 - 2 * ((+ 60-30 (- 40.0 / 5) * (9-2 * 5/3 + 7/99 * 3/4 * 2998 + 10 * 568/14)) - (* -4. 3) / (16-3 * 2)) ", '*' * 20 is 
    # INPp = '. 1 - 2 * ((+ 60-30 (- 40.0 /. 5) * (9-2. 5 * /. 7. 3 + / 99. 3 * / * 2998 +10 * 568/14. 4)) - (* -4. 3) / (16-3 * 2)) ' 
    INPp = " 1-2 * -30 / -12 * (-20 + -3 * 200 is / -200 * -300-100) " 
    # INPp =" 980.0 * 1-5 " 
    INPp the re.sub = ( ' \ S * ' , '', inpp)
     #Expression stored in the list, 
    the Result = exec_bracket (the INPp)
     Print the Result
Code Calculator

 

Guess you like

Origin www.cnblogs.com/caixiaowu/p/12349758.html