1. 程式人生 > >刷題 -- python計算器練習題

刷題 -- python計算器練習題

練習題 python

假設python只能簡單處理+-/,不能處理括號。練習處理。練習正則。
網上有些無法很好處理負號,如下情況。暫未處理括號數字間缺少
等情況。
(-1+(2-5(-1))(2-5))
-1+(2-5)*(2-5)

#/usr/bin/env python3
#mail [email protected]
import  re,sys

symbos_map={‘+-‘:‘-‘,‘++‘:‘+‘,‘-+‘:‘-‘,‘--‘:‘+‘}
# -1-(-1)*-1 =-2 #過程 -1--1*-1 => -1-- -1  => -1+-1 => -1-1 => -2
# 找最內括號,數字後面無符號,去除括號
# 找最內括號,有表示式,先乘除,乘除 從數字開始匹配, 1*-1 1*1
# 乘除完成,從左到右,帶符號匹配。  -1+-1 不等於 -(1-1) ,需要處理-1-------1 情況(由於乘除時未處理符號)
def calc_element_3(v1,v2,symbol):
    print("計算: %s,%s,%s"%(v1,v2,symbol))
    ‘‘‘帶符號 + - * / ‘‘‘
    v1,v2=float(v1),float(v2)
    if symbol==‘+‘:return v1+v2
    elif symbol ==‘-‘:return v1-v2
    elif symbol == ‘*‘:return v1*v2
    elif symbol ==‘/‘:return v1/v2
    else:print(symbol);sys.exit()

def multi_divi(s):
    ‘‘‘ s括號內表達式,用於處理乘除。找到1*-2,處理為-2 ,處理1次 ‘‘‘
    print("處理乘除: %s"%s)
    re_seach_obj=re.search(r‘([0-9.]+)([*/])([+-])?([0-9.]+)‘,s)
    if re_seach_obj is not None:
        s_match_str = re_seach_obj.group(0)  # 1*-1
        value1=re_seach_obj.group(1)
        value2=re_seach_obj.group(4)
        simblos=re_seach_obj.group(2)
        simblo_ext=re_seach_obj.group(3)
        ret=calc_element_3(value1,value2,simblos)
        ret=simblo_ext+str(ret)
        print(s_match_str,ret)
        s=s.replace(s_match_str,ret)
        return s
# res=multi_divi(‘-1-2*-2‘) # print(res)

def add_minu(s):
    print("處理加減: %s"%s)
    ‘‘‘ -1--1,1--1,-1+1,-1---1,-1---------1,用於從左往右處理加減,處理1次‘‘‘
    if re.search(r‘[*/]‘, s):
        print("should do * / before + -: %s"%s)
        sys.exit()

    while re.search(r‘[+\-*\\]{2,}‘,s):     #-1-1 ,1+++++1 => -1-1 , 1+1
        for symbos_key in symbos_map:
            s=s.replace(symbos_key,symbos_map[symbos_key])
    # print(s)
    re_seach_obj = re.search(r‘([+-]?[0-9.]+)([+-])([0-9.]+)‘, s)
    if re_seach_obj:
        s_match_str = re_seach_obj.group(0)  # 1*-1
        value1=re_seach_obj.group(1)
        value2=re_seach_obj.group(3)
        simblos=re_seach_obj.group(2)
        ret=calc_element_3(value1,value2,simblos)
        # print(s_match_str,ret)
        s=s.replace(s_match_str,str(ret))
        # print(s)
        return s
# res=add_minu(‘1.0+1.5++++1‘)

def handler_expression(expression):
    print("進入表達式處理%s"%expression)
    while re.search(‘[*/]‘,expression):
        expression=multi_divi(expression)
    while re.search(‘[0-9.]+[+-]+[0-9.]+‘,expression):
        expression=add_minu(expression)
    return expression
# res=handler_expression(‘-1+---5*-2/-1++2+2+2‘) # print(res)

# a=handler_expression(‘1+2--5.0*-3.0‘)
# print(a)

def hadler_braces(s):
    print(s)
    flag=True
    while flag:
        re_obj=re.search(‘\([+\-*/0-9.]*\)‘,s)
        if re_obj:
            s_match_str=re_obj.group(0)
            print("括號匹配: %s"%s_match_str)
            if re.match(‘\([+\-]?([0-9.]*)\)‘,s_match_str):
                print("僅剩余單個值: %s"%s_match_str)
                s_match_str_match=re.match(‘\(([+\-]?[0-9.]*)\)‘,s_match_str).group(1)
                s = s.replace(s_match_str, s_match_str_match)
                print(s)

            else:
                print("調用處理%s"%s_match_str)
                s_match_str_str=re.search(‘\(([+\-*/0-9.]*)\)‘,s).group(1)

                ret=handler_expression(s_match_str_str)
                s = s.replace(s_match_str, str(ret))
                print(s)
        else:
            flag=False
    return s

# no_braces_result=hadler_braces(‘(-1+(2-5*(-1))*(2-5))‘)
# result=handler_expression(no_braces_result)
# print(result)

if __name__ == ‘__main__‘:
    while True:
        exp=input("輸入表達式: ")
        exp=re.sub(‘\s‘,‘‘,exp)
        no_braces_result=hadler_braces(str(exp))
        result=handler_expression(no_braces_result)
        print(result)

刷題 -- python計算器練習題