@本文來源於公衆號:csdn2299,喜歡可以關注公衆號 程序員學府
這篇文章主要介紹了Python 70行代碼實現簡單算式計算器解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
描述:用戶輸入一系列算式字符串,程序返回計算結果。
要求:不使用eval、exec函數。
實現思路:找到當前字符串優先級最高的表達式,在算術運算中,()優先級最高,則取出算式最底層的(),再進行加減乘除運算。對於加減乘除,也要確立一個優先級,可以使用一個運算符列表,用for循環逐個處理運算符,並且要考慮同級情況(如for遍歷至*時,也要考慮同級別的\是否要提前運算)。不斷循環上述過程,直到最終得到一個結果。
關鍵點:使用re模塊匹配出當前狀態下優先級最高的算式。
result = re.search(’([^()]+)’,s)
代碼奉上
mport re
'''根據本邏輯,‘-'必須早於‘+'循環 否則特殊情況會報錯
原因是若出現符號--,會被處理爲+,若+優先遍歷,最後+將無法被處理'''
oper_char = ['^','*','/','-','+']
def format_str(s):
'''除去空格和兩邊括號'''
return s.replace(' ','').replace('(','').replace(')','')
def handle_symbol(s):
'''處理多個運算符並列的情況'''
return s.replace('+-','-').replace('--','+').replace('-+','-').replace('++','+')
def cal(x,y,opertor):
'''加減乘除開方'''
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):
'''無括號運算 返回一個浮點數
symbol用於判斷返回值是正還是負'''
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('-','負').replace('+','-').replace('負','+')
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):
'''獲取優先級最高的表達式'''
res = re.search('\([^()]+\)',s)
if res != None:return res.group()
if __name__ == '__main__':
while True:
s1 = input('請輸入您要計算的表達式(支持加減乘除開方): ')
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)))
非常感謝你的閱讀
大學的時候選擇了自學python,工作了發現吃了計算機基礎不好的虧,學歷不行這是沒辦法的事,只能後天彌補,於是在編碼之外開啓了自己的逆襲之路,不斷的學習python核心知識,深入的研習計算機基礎知識,整理好了,我放在我們的微信公衆號《程序員學府》,如果你也不甘平庸,那就與我一起在編碼之外,不斷成長吧!
其實這裏不僅有技術,更有那些技術之外的東西,比如,如何做一個精緻的程序員,而不是“屌絲”,程序員本身就是高貴的一種存在啊,難道不是嗎?[點擊加入]想做你自己想成爲高尚人,加油!