Python 練習: 計算機

來源:互聯網
上載者:User

標籤:return   reg   int   格式   arch   for   numbers   add   lse   

import redef format_string(s):             # 對錶達式進行格式化    s = s.replace(‘ ‘, ‘‘)    s = s.replace("--", "+")    s = s.replace("++", "+")    s = s.replace("+-", "-")    s = s.replace("*+", "*")    s = s.replace("/+", "/")    return sdef check_expression(s):          # 對錶達式進行檢測    flag = True    if not s.count("(") == s.count(")"):        print("括弧沒有閉合")        flag = False    if re.findall(‘[a-z]+‘, s.lower()):        print("有非法字元")        flag = False    return flagdef calc_mul_div(s):    regular = ‘[\-]?\d+\.?\d*[*/][\-]?\d+\.?\d*‘    while re.findall(regular, s):        expression = re.search(regular, s).group()        if expression.count("*"):          # 判斷是否是乘法            x, y = expression.split("*")            mul_result = str(float(x) * float(y))            s = s.replace(expression, mul_result)            s = format_string(s)        if expression.count("/"):          # 判斷是否是除法            x, y = expression.split(‘/‘)            div_result = str(float(x) / float(y))            s = s.replace(expression, div_result)            s = format_string(s)    return sdef calc_add_sub(s):                       # 判斷加減法    add_regular = ‘[\-]?\d+\.?\d*\+[\-]?\d+\.?\d*‘    sub_regular = ‘[\-]?\d+\.?\d*\-[\-]?\d+\.?\d*‘    while re.findall(add_regular, s):        add_list = re.findall(add_regular, s)        for add_str in add_list:            x, y = add_str.split("+")            add_result = "+" + str(float(x) + float(y))            s = s.replace(add_str, add_result)        s = format_string(s)    while re.findall(sub_regular, s):        sub_list = re.findall(sub_regular, s)        for sub_str in sub_list:            numbers = sub_str.split("-")            if len(numbers) == 3:      # 如果運算式類似 -1-1,則 list 是 [‘‘, ‘1‘, ‘1‘] ,                                       # 如果運算式類似 8-2, 則 list 是 [‘8‘, ‘2‘]                result = 0                for v in numbers:                    if v:                        result -= float(v)            else:                x, y = numbers                result = float(x) - float(y)            s = s.replace(sub_str, "+" + str(result))        s = format_string(s)    return sif __name__ == "__main__":    s = ‘(( 2 /1 * 7 ) - ( 3 *4 ) )‘    if check_expression(s):        s = format_string(s)        while s.count("(") > 0:            strs = re.search(‘\([^()]*\)‘, s).group()            replace_str = calc_mul_div(strs)            replace_str = calc_add_sub(replace_str)            s = format_string(s.replace(strs, replace_str[1:-1]))  # 去掉多餘的括弧        else:            replace_str = calc_mul_div(s)            replace_str = calc_add_sub(replace_str)            s = s.replace(s, replace_str)        print("result: ", s.replace("+", ""))運行結果:result:  2.0

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.