用python實現複雜公式的計算機功能

來源:互聯網
上載者:User

標籤:lse   not   mat   計算   res   int   小數點   字母   再計算   

 給出一段如下行,比較複雜的運算公式,自己編寫代碼計算 1 - 2.99 * ( (60.2-30 +( -40/ 5) * (9-2*5/3 + 7 /3*99/4*2998 +10.5 * 568/14 )) - (-4*3)/ (16-3*2) )  思路:step1.需要先檢查合法性,檢測有無字母及其他的非運算的非法字元step2.格式化公式,去除空格,替換(--,+-,-+,++)之類的雙運算子為(+,-,-,+)step3.先計算()內的乘除,加減,然後再計算最後不含()的乘除,加減

# 檢查公式的合法性,有無非法字元def check(s):    if not s.count(‘(‘) == s.count(‘)‘):        print(‘請檢查,括弧未閉合‘)    elif re.findall(‘[[email protected]#$]‘, ‘s‘) is not None:        print(‘請檢查,該公式含有非法符號‘)    elif re.findall(‘[a-zA-Z]‘, ‘s‘) is not None:        print(‘請檢查,該公式含有字母‘)    elif s >= u‘\u4e00‘ and s <= u‘\u9fa5‘:        print(‘請檢查,該公式含有中文‘)# 格式化公式,去除空格,重新定義雙符號def formats(s):    s = s.replace(‘ ‘, ‘‘)    s = s.replace(‘++‘, ‘+‘)    s = s.replace(‘--‘, ‘+‘)    s = s.replace(‘+-|-+‘, ‘-‘)    s = s.replace(‘*+‘, ‘*‘)    s = s.replace(‘/+‘, ‘/‘)    return s
取數字和帶小數點的方法,2種結果都一樣,注意體會
ret = re.findall(r‘[\d\.]+‘, ‘numbrt 1.58 abc 123‘)
print(ret) # [‘1.58‘, ‘123‘]
ret = re.findall(‘\d\.?\d*‘, ‘numbrt 1.58 abc 123‘)
print(ret) # [‘1.58‘, ‘123‘]

def cheng_chu(s):  # 處理帶負號的乘除    s = formats(s)    r = re.compile(r‘[\d\.]+[\*/]-?[\d\.]+‘)    while re.search(r‘[\*/]‘, s):        ma = re.search(r, s).group()        # print(ma)        li = re.findall(r‘(-?[\d\.]+|\*|/)‘, ma)        if li[1] == ‘*‘:            result = str(float(li[0]) * float(li[2]))        else:            result = str(float(li[0]) / float(li[2]))        s = s.replace(ma, result, 1)    return sdef jia_jian(s):  # 處理加減法,變成數組,全加    s = formats(s)    li = re.findall(r‘([\d\.]+|\+|-)‘, s)    nums = 0    for i in range(len(li)):        if li[i] == ‘-‘:            li[i] = ‘+‘            li[i + 1] = float(li[i + 1]) * -1    for i in li:        if i == ‘+‘:            i = 0        nums = nums + float(i)    return str(nums)def simple(x):  # 處理不帶括弧的    return jia_jian(cheng_chu(x))def jiSuan(x):  # 處理帶括弧的    while ‘(‘ in x:        reg = re.compile(r‘\([^\(\)]+\)‘)        ma = re.search(reg, x).group()        result = simple(ma[1:-1])        x = x.replace(ma, result, 1)    return simple(x)
ss = ‘1 - 2.99 * ( (60.2-30 +( -40/ 5) * (9-2*5/3 + 7 /3*99/4*2998 +10.5 * 568/14 )) - (-4*3)/ (16-3*2) )‘.replace(‘ ‘, ‘‘)print(‘你的計算結果:‘, jiSuan(ss))print(‘eval計算結果:‘, eval(ss))

後面測試階段就奇怪了:

if jiSuan(ss) == eval(ss):
print(‘計算正確,你很棒喲 @[email protected]‘)
else:
print(‘計算不正確,請重新來過!‘)

# 這裡很奇怪,要是不str(),直接比較,就會顯示‘計算不正確’,難道後面還有小數點嗎?
if str(jiSuan(ss)) == str(eval(ss)):
print(‘計算正確,你很棒喲 @[email protected]‘)
else:
print(‘計算不正確,請重新來過!‘)

請大佬指點.

用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.