标签:not 解析 inpu group log put 简单 val 功能
开发一个简单的python计算器
1 #1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2)) 2 import re 3 4 def choice(): 5 #得到用户输入的算式 6 num = ‘‘.join(input(‘计算器启动:‘).split()) 7 #进入循环拆分 8 while True: 9 if ‘(‘ in num: 10 ct = re.search(r‘\(([^()]+)\)‘, num) 11 if ct is not None: 12 b = ct.groups()[0] 13 c = count(b) 14 num = re.sub(r‘\(([^()]+)\)‘, str(c), num, 1) 15 else: 16 c = count(num) 17 print(c) 18 break 19 # 乘除式 20 def mul(num): 21 b = re.search(r‘\d+\.?\d*(\*-?\d+\.?\d*)+‘, num) 22 if b is not None: 23 b = b.group() 24 rest = 1 25 c = re.findall(r‘-?\d+\.?\d*‘, b) 26 ls = [] 27 for item in c: 28 ls.append(float(item)) 29 for i1 in range(len(ls)): 30 rest = rest * ls[i1] 31 a = re.sub(r‘\d+\.?\d*(\*-?\d+\.?\d*)+‘, str(rest), num, 1) 32 return a 33 #加减法 34 def add(num): 35 if ‘--‘ in num: 36 num = num.replace(‘--‘, ‘+‘) 37 c = re.findall(r‘-?\d+\.?\d*‘, num) 38 ls = [] 39 for i in c: 40 ls.append(float(i)) 41 rest = sum(ls) 42 return rest 43 #开始计算 44 def run(num): 45 b = re.search(r‘\d+\.?\d*(\/-?\d+\.?\d*)+‘, num) 46 if b is not None: 47 b = b.group() 48 c = re.findall(r‘-?\d+\.?\d*‘, b) 49 ls =[] 50 for i in c: 51 ls.append(float(i)) 52 rest = ls[0] 53 for i1 in range(1,len(ls)): 54 rest = rest / ls[i1] 55 num = re.sub(r‘\d+\.?\d*(\/-?\d+\.?\d*)+‘, str(rest), num, 1) 56 return num 57 #得到结果 58 def count(b): 59 while True: 60 if ‘*‘ in b: 61 c = b.split(‘*‘) 62 if ‘/‘ in c[0]: 63 b = run(b) 64 else: 65 b = mul(b) 66 elif ‘/‘ in b: 67 b = run(b) 68 69 elif ‘+‘ or ‘-‘ in b: 70 b = add(b) 71 return b 72 else: 73 return b 74 choice()
标签:not 解析 inpu group log put 简单 val 功能
原文地址:http://www.cnblogs.com/gz369521/p/6791360.html