Python 70行代碼實(shí)現(xiàn)簡(jiǎn)單算式計(jì)算器解析
描述:用戶(hù)輸入一系列算式字符串,程序返回計(jì)算結(jié)果。
要求:不使用eval、exec函數(shù)。
實(shí)現(xiàn)思路:找到當(dāng)前字符串優(yōu)先級(jí)最高的表達(dá)式,在算術(shù)運(yùn)算中,()優(yōu)先級(jí)最高,則取出算式最底層的(),再進(jìn)行加減乘除運(yùn)算。對(duì)于加減乘除,也要確立一個(gè)優(yōu)先級(jí),可以使用一個(gè)運(yùn)算符列表,用for循環(huán)逐個(gè)處理運(yùn)算符,并且要考慮同級(jí)情況(如for遍歷至*時(shí),也要考慮同級(jí)別的\是否要提前運(yùn)算)。不斷循環(huán)上述過(guò)程,直到最終得到一個(gè)結(jié)果。
關(guān)鍵點(diǎn):使用re模塊匹配出當(dāng)前狀態(tài)下優(yōu)先級(jí)最高的算式。
result = re.search('\([^()]+\)',s)
實(shí)現(xiàn)代碼:
import re
'''根據(jù)本邏輯,‘-'必須早于‘+'循環(huán) 否則特殊情況會(huì)報(bào)錯(cuò)
原因是若出現(xiàn)符號(hào)--,會(huì)被處理為+,若+優(yōu)先遍歷,最后+將無(wú)法被處理'''
oper_char = ['^','*','/','-','+']
def format_str(s):
'''除去空格和兩邊括號(hào)'''
return s.replace(' ','').replace('(','').replace(')','')
def handle_symbol(s):
'''處理多個(gè)運(yùn)算符并列的情況'''
return s.replace('+-','-').replace('--','+').replace('-+','-').replace('++','+')
def cal(x,y,opertor):
'''加減乘除開(kāi)方'''
if opertor == '^':return x**y
elif opertor == '*':return x*y
elif opertor == '/':return x/y
elif opertor == '+':return x+y
elif opertor == '-':return x-y
def Bottom_operation(s):
'''無(wú)括號(hào)運(yùn)算 返回一個(gè)浮點(diǎn)數(shù)
symbol用于判斷返回值是正還是負(fù)'''
symbol = 0
s = handle_symbol(s)
for c in oper_char:
while c in s:
id,char = (s.find(c),c)
if c in ('*','/') and '*' in s and '/' in s:
ids,idd = (s.find('*'),s.find('/'))
id,char = (ids,'*') if ids <= idd else (idd,'/')
if c in ('+','-') and '+' in s and '-' in s:
ida,idd = (s.find('+'),s.find('-'))
id,char = (ida,'+') if ida <= idd else (idd,'-')
if id == -1:break
left,right = ('','')
for i in range(id - 1,-1,-1):
if s[i] in oper_char:break
left = s[i] + left
for i in range(id + 1,len(s)):
if s[id+1] == '-':
right += s[i]
continue
if s[i] in oper_char:break
right += s[i]
if right == '' or left == '':
if s[0] in ('-','+'):
if '+' not in s[1:] and '-' not in s[1:]:break
s = s[1:].replace('-','負(fù)').replace('+','-').replace('負(fù)','+')
symbol += 1
continue
else:return '輸入算式有誤'
old_str = left + char + right
new_str = str(cal(float(left),float(right),char))
s = handle_symbol(s.replace(old_str,new_str))
return float(s) if symbol % 2 == 0 else -float(s)
def get_bottom(s):
'''獲取優(yōu)先級(jí)最高的表達(dá)式'''
res = re.search('\([^()]+\)',s)
if res != None:return res.group()
if __name__ == '__main__':
while True:
s1 = input('請(qǐng)輸入您要計(jì)算的表達(dá)式(支持加減乘除開(kāi)方): ')
while get_bottom(s1) != None:
source = get_bottom(s1)
result = Bottom_operation(format_str((source)))
s1 = s1.replace(source,str(result))
print(Bottom_operation(format_str(s1)))
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python調(diào)用DLL與EXE文件截屏對(duì)比分析
這篇文章主要為大家介紹了python調(diào)用DLL與EXE文件截屏對(duì)比分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2021-10-10
在Keras中CNN聯(lián)合LSTM進(jìn)行分類(lèi)實(shí)例
這篇文章主要介紹了在Keras中CNN聯(lián)合LSTM進(jìn)行分類(lèi)實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
Python利用代理ip實(shí)現(xiàn)自動(dòng)化爬蟲(chóng)任務(wù)管理
本文主要介紹了Python利用代理ip實(shí)現(xiàn)自動(dòng)化爬蟲(chóng)任務(wù)管理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
Python基于gevent實(shí)現(xiàn)文件字符串查找器
這篇文章主要介紹了Python基于gevent實(shí)現(xiàn)文件字符串查找器,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
Python可視化Matplotlib介紹和簡(jiǎn)單圖形的繪制
這篇文章主要介紹了Python可視化Matplotlib介紹和簡(jiǎn)單圖形的繪制,文中附含詳細(xì)示例代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-09-09
NDArray 與 numpy.ndarray 互相轉(zhuǎn)換方式
這篇文章主要介紹了NDArray 與 numpy.ndarray 互相轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
python ndarray數(shù)組對(duì)象特點(diǎn)及實(shí)例分享
在本篇文章里小編給大家分享的是一篇關(guān)于python ndarray數(shù)組對(duì)象特點(diǎn)及實(shí)例相關(guān)內(nèi)容,有需要的朋友們跟著學(xué)習(xí)下。2021-10-10

