要求:
- 实现加减乘除及拓号优先级解析
- 用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等类似公式后,必须自己解析里面的(),+,-,*,/符号和公式(不能调用eval等类似功能偷懒实现),运算后得出结果,结果必须与真实的计算器所得出的结果一致
1 import re 2 3 def main(): 4 5 a = ‘‘.join(input(‘请输入需要计算的算式‘).split()) 6 7 while True: 8 if ‘(‘ in a: 9 ct = re.search(r‘\(([^()]+)\)‘, a) 10 if ct is not None: 11 b = ct.groups()[0] 12 c = count(b) 13 a = re.sub(r‘\(([^()]+)\)‘, str(c), a, 1) 14 else: 15 c = count(a) 16 print(c) 17 break 18 19 def add_min(a): 20 ‘‘‘ 21 计算加减法 22 :param: 23 :return: 24 ‘‘‘ 25 26 if ‘--‘ in a: 27 a = a.replace(‘--‘, ‘+‘) 28 29 c = re.findall(r‘-?\d+\.?\d*‘, a) 30 ls = [] 31 for i in c: 32 ls.append(float(i)) 33 rest = sum(ls) 34 return rest 35 36 37 def mul(a): 38 ‘‘‘ 39 计算剩数 40 :param ct: 41 :return: 42 ‘‘‘ 43 44 45 b = re.search(r‘\d+\.?\d*(\*-?\d+\.?\d*)+‘, a) 46 if b is not None: 47 b = b.group() 48 rest = 1 49 c = re.findall(r‘-?\d+\.?\d*‘, b) 50 ls =[] 51 for item in c: 52 ls.append(float(item)) 53 for i1 in range(len(ls)): 54 rest = rest * ls[i1] 55 a = re.sub(r‘\d+\.?\d*(\*-?\d+\.?\d*)+‘, str(rest), a, 1) 56 return a 57 58 59 60 def div(a): 61 ‘‘‘ 62 计算出发 63 :param a: 64 :return: 65 ‘‘‘ 66 67 b = re.search(r‘\d+\.?\d*(\/-?\d+\.?\d*)+‘, a) 68 if b is not None: 69 b = b.group() 70 c = re.findall(r‘-?\d+\.?\d*‘, b) 71 ls =[] 72 for i in c: 73 ls.append(float(i)) 74 rest = ls[0] 75 for i1 in range(1,len(ls)): 76 rest = rest / ls[i1] 77 a = re.sub(r‘\d+\.?\d*(\/-?\d+\.?\d*)+‘, str(rest), a, 1) 78 return a 79 80 81 def count(b): 82 ‘‘‘ 83 计算结果 84 :return: 85 ‘‘‘ 86 while True: 87 if ‘*‘ in b: 88 c = b.split(‘*‘) 89 if ‘/‘ in c[0]: 90 b = div(b) 91 else: 92 b = mul(b) 93 elif ‘/‘ in b: 94 b = div(b) 95 96 elif ‘+‘ or ‘-‘ in b: 97 b = add_min(b) 98 return b 99 else: 100 return b 101 102 103 104 105 main()
时间: 2024-10-09 17:51:06