使用python实现一个计算器
一个简单的python计算器
1、实现加减乘除及拓号优先级解析
2、用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等类似公式后,必须自己解析里面的(),+,-,*,/符号和公式(不能调用eval等类似功能偷懒实现),运算后得出结果,结果必须与真实的计算器所得出的结果一致
#__author: Tiger li #date: 2016/9/12 # in python 3.5 import re # 对字符串进行格式化输出,判断是否有字母,空格,有字母报错,有空格替换成空,是否有双重运算符号,将其替换成单个 def space(r): if re.search('[a-zA-Z]',r): print ("输入错误,请重新输入: ") else: r = re.sub('\++', '+', r) r = re.sub('\+-', '-', r) r = re.sub('\--', '+', r) r = re.sub('\-\+', '-', r) r = re.sub('\*\*', '*', r) r = re.sub('\/\/', '/', r) r = re.sub(' ', '', r) return r #乘除运算函数 def me(s): while re.search('[*, /]', s): g = re.search('[\-]?\d+\.?\d*[*/][\-]?\d+\.?\d*', s).group() fh = re.search('[*/]', g).group() if fh == '*': #执行乘法运算 x,y = re.split('[*/]', g) sum = float(x) * float(y) else: #执行除法运算 x,y = re.split('[*/]', g) sum = float(x) / float(y) s = s.replace(g, '+'+str(sum)) s=space(s) return s #加减运算函数 def pl(t): while re.search('[\-]?\d+\.?\d*[+-][\-]?\d+\.?\d*', t): g = re.search('[\-]?\d+\.?\d*[+-][\-]?\d+\.?\d*', t).group() if re.search('[\-]?\d+\.?\d*[+][\-]?\d+\.?\d*',g): #执行加法运算 ret = re.split('[+]', g) sum = float(ret[0]) + float(str('+') + str(ret[-1])) t = t.replace(g, str(sum)) t=space(t) elif re.search('[\-]?\d+\.?\d*[\-][\-]?\d+\.?\d*',g): #执行减法运算 ret=g.split('-') if len(ret)==2: s=float(ret[0])-float(ret[1]) t=t.replace(g,str(s)) t = space(t) elif len(ret)==3: x, y, z = ret s=-float(y)-float(z) t = t.replace(g, str(s)) t = space(t) return t #逻辑运算函数 def operation(j): while re.search('[\-]?\d+\.?\d*[*/][\-]?\d?\.?\d*', j): j = me(j) while re.search('[\-]?\d+\.?\d*[+-][\-]?\d?\.?\d*', j): j = pl(j) return j # source='1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )' source = input("请输入运算式>>>>>: ") # 对字符串进行匹配并运算 while re.search('\([^()]+\)', source): source = space(source) f = re.search('\([^()]+\)', source).group() d = f[1:-1] s1 = operation(d) source = source.replace(f, s1) else: source = operation(source) print (source)
作者:TigerLee
出处:http://www.cnblogs.com/tiger666/
本文版权归作者和博客园所有,欢迎转载。转载请在留言板处留言给我,且在文章标明原文链接,谢谢!
如果您觉得本篇博文对您有所收获,觉得我还算用心,请点击右下角的 [推荐],谢谢!

浙公网安备 33010602011771号