week5: develop a simple Python calculator

# - * - Coding: UTF-. 8 - * - 
# @time: 2019 / X / X 
# @author: the root 

Import Re 


operatorDict = { 
    '+': the lambda A, B: a float (A) + a float (B), 
    '-': the lambda A, B: a float (A) - a float (B), 
    '*': the lambda A, B: a float (A) * a float (B), 
    '/': the lambda A, B: a float (A ) / a float (B), 
} 

DEF Calculator (= expression The '. 1 - 2 * ((+ 60-30 (- 40/5) * (. 5 * 9-2 / +. 3' 
                          '. 7 /. 3 * 99 / *. 4 2998 + 10 * 568/14)) - (-4 * 3) / (16-3 * 2)) '): 
    ' '' 
    calculator 
    total logic: 
        1. first, find the inner bracket, and then calculate the inside final value, with the final value replaces the original expressions 
        2. then above process is repeated 
    without brackets portion computation logic: 
        1. truncate numbers and a list of operators, may comprise a digital negative sign; 
        2.Value calculation in the list and replaced after the first subtraction multiplication and division;
    : param expression: string expression 
        the while I <len (L2):
    : return: Calcd expression 
    '' ' 

    Print ( "correct answer is:", the eval (expression The)) 


    DEF calWithOutBrackets (= expression The' -. 1 + 2 *. 3 / 4-5 * -3 '): 
        # truncated to digital and a list of operators 
        for I in operatorDict: 
            expression the expression.replace = (I, 'S' + I + 'S') 
        L = expression.split ( 'S') 
        L2 = [] 
        I = 0 
        the while I <len (L): 
            L IF [I] == '': 
                l2.append (L [I +. 1] + L [I + 2]) 
                I 2 + = 
            the else: 
                l2.append (L [I]) # negatively signed number without and operator 
            I + =. 1 
        # multiplication and division calculation 
        I =. 1 
            IF L2 [I] in [ '*', '/']:
                l2[i-1:i+2] = [operatorDict[l2[i]](l2[i-1],l2[i+1])]
            else:
                i+=2
        # 运算加减
        while len(l2)>1:
            l2[0:3] = [operatorDict[l2[1]](l2[0], l2[2])]
        return str(l2[0])

    expression=expression.replace(' ','')
    check = re.search('\([^\(\)]+\)', expression)
    while check:
        checkValue = check.group()
        # print(checkValue)
        expression = expression.replace(checkValue, calWithOutBrackets(checkValue[1:-1]))
        check = re.search('\([^\(\)]*\)', expression)
    else:
        return calWithOutBrackets(expression)


the __name__ == IF '__main__': 
    Re = Calculator () 
    Print ( "Actual result:", re)

  

Guess you like

Origin www.cnblogs.com/codecca/p/11991410.html