开发一个简单的python计算器
- 实现加减乘除及拓号优先级解析
- 用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等类似公式后,必须自己解析里面的(),+,-,*,/符号和公式(不能调用eval等类似功能偷懒实现),运算后得出结果,结果必须与真实的计算器所得出的结果一致
hint:
re.search(r'([^()]+)',s).group()
'(-40/5)'
- 输入用re搜索返回NONE的情况,也就是输入了全部是英文字母的情况;
- 输入的括号,左括号和右括号的个数不匹配的情况,肯定少输入;
- 输入含有非数字以及加减乘除或者括号的情况;搜索返回的字符的个数小于用户输入的长度;
# !/usr/bin/env python # -*- coding:utf-8 -*- # Author:lzd import re def main(): while True: a=input("请输入你想计算的数学方程式,先小括号(请输入半角的括号,不要输入中文的),后加减乘除 ") #a=' 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )' a = a.replace(' ', '') # print(a) if re.search(r"[0-9+-*/().]+", a) == None: print("匹配失败,输入格式错误,请重新输入 ") continue elif a.count('(') != a.count(')'): print('你写的括号左右个数不匹配') continue elif len(re.search(r"[0-9+-*/().]+", a).group()) != len(a): print("输入格式错误,请重新输入 ") continue else: while True: if '(' in a: ct = re.search(r'([^()]+)', a) #计算出第一个()里的算式 if ct is not None: b = ct.group() c = chengfa_chufa(b) a = re.sub(r'(([^()]+))', str(c), a, 1) print(a) else: c = chengfa_chufa(a) print(c) break break def jiajianfa(a): ''' 计算加减法 :param: :return: ''' if '--' in a: a = a.replace('--', '+') c = re.findall(r'-?d+.?d*', a) #-123456.132123 ls = [] for i in c: ls.append(float(i)) rest = sum(ls) return rest def chengfa(a): ''' 计算乘法 :param ct: :return: ''' b = re.search(r'd+.?d*(*-?d+.?d*)+', a) #132132.654645*-564564.456456*-5645645.654561651615 if b is not None: b = b.group() rest = 1 c = re.findall(r'-?d+.?d*', b) ls = [] for item in c: ls.append(float(item)) for i1 in range(len(ls)): rest = rest * ls[i1] a = re.sub(r'd+.?d*(*-?d+.?d*)+', str(rest), a, 1) return a def chufa(a): ''' 计算出发 :param a: :return: ''' b = re.search(r'd+.?d*(/-?d+.?d*)+', a) #523.5564561/-1231.564564/-1344.4546 if b is not None: b = b.group() c = re.findall(r'-?d+.?d*', b) ls = [] for i in c: ls.append(float(i)) rest = ls[0] for i1 in range(1, len(ls)): rest = rest / ls[i1] a = re.sub(r'd+.?d*(/-?d+.?d*)+', str(rest), a, 1) return a def chengfa_chufa(b): ''' 计算结果 :return: ''' while True: if '*' in b: c = b.split('*') if '/' in c[0]: b = chufa(b) else: b = chengfa(b) elif '/' in b: b = chufa(b) elif '+' or '-' in b: b = jiajianfa(b) return b else: return b main()