刷題 -- python計算機練習題

來源:互聯網
上載者:User

標籤:練習題   python   

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

#/usr/bin/env python3#mail [email protected]import  re,syssymbos_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計算機練習題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.