Python 70行代码实现简单算式计算器解析
描述:用户输入一系列算式字符串,程序返回计算结果。
要求:不使用eval、exec函数。
实现思路:找到当前字符串优先级最高的表达式,在算术运算中,()优先级最高,则取出算式最底层的(),再进行加减乘除运算。对于加减乘除,也要确立一个优先级,可以使用一个运算符列表,用for循环逐个处理运算符,并且要考虑同级情况(如for遍历至*时,也要考虑同级别的\是否要提前运算)。不断循环上述过程,直到最终得到一个结果。
关键点:使用re模块匹配出当前状态下优先级最高的算式。
result=re.search('\([^()]+\)',s)
实现代码:
importre
'''根据本逻辑,‘-'必须早于‘+'循环否则特殊情况会报错
原因是若出现符号--,会被处理为+,若+优先遍历,最后+将无法被处理'''
oper_char=['^','*','/','-','+']
defformat_str(s):
'''除去空格和两边括号'''
returns.replace('','').replace('(','').replace(')','')
defhandle_symbol(s):
'''处理多个运算符并列的情况'''
returns.replace('+-','-').replace('--','+').replace('-+','-').replace('++','+')
defcal(x,y,opertor):
'''加减乘除开方'''
ifopertor=='^':returnx**y
elifopertor=='*':returnx*y
elifopertor=='/':returnx/y
elifopertor=='+':returnx+y
elifopertor=='-':returnx-y
defBottom_operation(s):
'''无括号运算返回一个浮点数
symbol用于判断返回值是正还是负'''
symbol=0
s=handle_symbol(s)
forcinoper_char:
whilecins:
id,char=(s.find(c),c)
ifcin('*','/')and'*'insand'/'ins:
ids,idd=(s.find('*'),s.find('/'))
id,char=(ids,'*')ifids<=iddelse(idd,'/')
ifcin('+','-')and'+'insand'-'ins:
ida,idd=(s.find('+'),s.find('-'))
id,char=(ida,'+')ifida<=iddelse(idd,'-')
ifid==-1:break
left,right=('','')
foriinrange(id-1,-1,-1):
ifs[i]inoper_char:break
left=s[i]+left
foriinrange(id+1,len(s)):
ifs[id+1]=='-':
right+=s[i]
continue
ifs[i]inoper_char:break
right+=s[i]
ifright==''orleft=='':
ifs[0]in('-','+'):
if'+'notins[1:]and'-'notins[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))
returnfloat(s)ifsymbol%2==0else-float(s)
defget_bottom(s):
'''获取优先级最高的表达式'''
res=re.search('\([^()]+\)',s)
ifres!=None:returnres.group()
if__name__=='__main__':
whileTrue:
s1=input('请输入您要计算的表达式(支持加减乘除开方):')
whileget_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)))
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。